@odatano/core 2.0.0-rc.4 → 2.0.0-rc.6

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 (35) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +28 -0
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  6. package/@cds-models/odatano/cardano/index.js +6 -0
  7. package/README.md +53 -3
  8. package/db/schema.cds +105 -0
  9. package/package.json +4 -3
  10. package/src/index.d.ts +6 -0
  11. package/src/index.js +21 -1
  12. package/src/plugin.js +33 -30
  13. package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
  14. package/srv/blockchain/backends/ogmios-backend.js +72 -5
  15. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  16. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  17. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  18. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  19. package/srv/cardano-agent-service.cds +150 -0
  20. package/srv/cardano-agent-service.d.ts +2 -0
  21. package/srv/cardano-agent-service.js +16 -0
  22. package/srv/cardano-indexer-service.cds +20 -0
  23. package/srv/cardano-indexer-service.js +3 -0
  24. package/srv/server.d.ts +2 -1
  25. package/srv/server.js +12 -0
  26. package/srv/utils/agent-grants-config.d.ts +64 -0
  27. package/srv/utils/agent-grants-config.js +144 -0
  28. package/srv/utils/agent-grants.d.ts +314 -0
  29. package/srv/utils/agent-grants.js +821 -0
  30. package/srv/utils/agent-token-auth.d.ts +106 -0
  31. package/srv/utils/agent-token-auth.js +239 -0
  32. package/srv/utils/liveness.d.ts +23 -0
  33. package/srv/utils/liveness.js +49 -0
  34. package/srv/utils/rate-limiter.d.ts +57 -0
  35. package/srv/utils/rate-limiter.js +126 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.4",
3
+ "version": "2.0.0-rc.6",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -45,7 +45,7 @@
45
45
  "axios": "^1.18.0",
46
46
  "esbuild": "0.28.1",
47
47
  "form-data": "^4.0.6",
48
- "fast-uri": "^3.1.5",
48
+ "fast-uri": "^3.1.7",
49
49
  "ws": "7.5.11",
50
50
  "@sap/approuter": {
51
51
  "body-parser": "^2.2.3"
@@ -141,7 +141,8 @@
141
141
  "pretest:unit": "npm run cds:types",
142
142
  "test:unit": "vitest run --project unit",
143
143
  "watch-odatano": "cds watch --open odatano/index.html?sap-ui-xx-viewCache=false --livereload false",
144
- "watch-wallet": "cds watch --open wallet/webapp/index.html"
144
+ "watch-wallet": "cds watch --open wallet/webapp/index.html",
145
+ "release:check": "node scripts/release-check.mjs"
145
146
  },
146
147
  "sapux": [
147
148
  "app/odatano"
package/src/index.d.ts CHANGED
@@ -4,6 +4,12 @@ export { CardanoIndexer } from '../srv/blockchain/cardano-indexer';
4
4
  export { CardanoTransactionBuilder } from '../srv/blockchain/cardano-tx-builder';
5
5
  export { getAppContext, getCardanoIndexer, getCardanoClient, getCardanoTxBuilder, loadConfigFromEnv, loadHsmConfigFromEnv, loadCrawlerConfigFromEnv, startCrawlerIfConfigured, loadWalletWorkerConfigFromEnv, startWalletWorkerIfConfigured, shutdownAppContext, } from '../srv/server';
6
6
  export { getHsmSigner } from '../srv/blockchain/signing/hsm-signer';
7
+ export { issueAgentGrant, updateAgentGrant, rotateAgentGrantToken, revokeAgentGrantById, getGrantUsage, resolveUsageWindow, hashAgentToken, AGENT_TOKEN_HEADER, AGENT_TOKEN_PREFIX, AGENT_ROLE, AGENT_ALLOWLISTABLE_ACTIONS, AGENT_ALWAYS_ALLOWED_EVENTS, } from '../srv/utils/agent-grants';
8
+ export type { IssueAgentGrantInput, IssuedAgentGrant, AgentGrantStatus, UpdateAgentGrantInput, UpdateAgentGrantResult, RotatedAgentGrant, AgentGrantUsage, GrantUsageCall, UsageWindow, } from '../srv/utils/agent-grants';
9
+ export { registerTransportLane } from '../srv/utils/agent-token-auth';
10
+ export type { TransportLane, LaneOutcome } from '../srv/utils/agent-token-auth';
11
+ export { loadAgentGrantsConfig } from '../srv/utils/agent-grants-config';
12
+ export type { AgentGrantsConfig } from '../srv/utils/agent-grants-config';
7
13
  export type { HsmConfig, HsmSignResult } from '../srv/utils/types';
8
14
  export { parseTransaction } from '../srv/cbor';
9
15
  export type { ParsedTransaction, ParsedInput, ParsedOutput, ParsedAsset, ParsedWitnesses, } from '../srv/cbor';
package/src/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.parseTransaction = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
39
+ exports.parseTransaction = exports.loadAgentGrantsConfig = exports.registerTransportLane = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
40
40
  exports.initialize = initialize;
41
41
  exports.shutdown = shutdown;
42
42
  exports.getStatus = getStatus;
@@ -65,6 +65,26 @@ Object.defineProperty(exports, "shutdownAppContext", { enumerable: true, get: fu
65
65
  // Re-export HSM signer for programmatic access
66
66
  var hsm_signer_1 = require("../srv/blockchain/signing/hsm-signer");
67
67
  Object.defineProperty(exports, "getHsmSigner", { enumerable: true, get: function () { return hsm_signer_1.getHsmSigner; } });
68
+ // Agent grants (v2.0, AGENT_GRANTS_DESIGN.md): the programmatic seams other
69
+ // packages build on — @odatano/x402 sells grants through issueAgentGrant and
70
+ // adds its payment lane through registerTransportLane.
71
+ var agent_grants_1 = require("../srv/utils/agent-grants");
72
+ Object.defineProperty(exports, "issueAgentGrant", { enumerable: true, get: function () { return agent_grants_1.issueAgentGrant; } });
73
+ Object.defineProperty(exports, "updateAgentGrant", { enumerable: true, get: function () { return agent_grants_1.updateAgentGrant; } });
74
+ Object.defineProperty(exports, "rotateAgentGrantToken", { enumerable: true, get: function () { return agent_grants_1.rotateAgentGrantToken; } });
75
+ Object.defineProperty(exports, "revokeAgentGrantById", { enumerable: true, get: function () { return agent_grants_1.revokeAgentGrantById; } });
76
+ Object.defineProperty(exports, "getGrantUsage", { enumerable: true, get: function () { return agent_grants_1.getGrantUsage; } });
77
+ Object.defineProperty(exports, "resolveUsageWindow", { enumerable: true, get: function () { return agent_grants_1.resolveUsageWindow; } });
78
+ Object.defineProperty(exports, "hashAgentToken", { enumerable: true, get: function () { return agent_grants_1.hashAgentToken; } });
79
+ Object.defineProperty(exports, "AGENT_TOKEN_HEADER", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_HEADER; } });
80
+ Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_PREFIX; } });
81
+ Object.defineProperty(exports, "AGENT_ROLE", { enumerable: true, get: function () { return agent_grants_1.AGENT_ROLE; } });
82
+ Object.defineProperty(exports, "AGENT_ALLOWLISTABLE_ACTIONS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALLOWLISTABLE_ACTIONS; } });
83
+ Object.defineProperty(exports, "AGENT_ALWAYS_ALLOWED_EVENTS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALWAYS_ALLOWED_EVENTS; } });
84
+ var agent_token_auth_1 = require("../srv/utils/agent-token-auth");
85
+ Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return agent_token_auth_1.registerTransportLane; } });
86
+ var agent_grants_config_1 = require("../srv/utils/agent-grants-config");
87
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_1.loadAgentGrantsConfig; } });
68
88
  // Re-export pure CBOR utilities (no CAP round-trip needed)
69
89
  var cbor_1 = require("../srv/cbor");
70
90
  Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return cbor_1.parseTransaction; } });
package/src/plugin.js CHANGED
@@ -52,32 +52,46 @@ if (!cds_1.default.env.requires) {
52
52
  if (!cds_1.default.env.requires.kinds) {
53
53
  cds_1.default.env.requires.kinds = {};
54
54
  }
55
+ /** The schema and the six CDS services this package ships, package-qualified. */
56
+ const PLUGIN_MODEL = [
57
+ '@odatano/core/db/schema',
58
+ '@odatano/core/srv/cardano-service',
59
+ '@odatano/core/srv/cardano-tx-service',
60
+ '@odatano/core/srv/cardano-sign-service',
61
+ '@odatano/core/srv/cardano-indexer-service',
62
+ '@odatano/core/srv/cardano-worker-service',
63
+ '@odatano/core/srv/cardano-agent-service'
64
+ ];
65
+ /** Relative `@impl` values used in the CDS files (rewritten in plugin mode, see below). */
66
+ const IMPL_PATHS = [
67
+ 'srv/cardano-service',
68
+ 'srv/cardano-tx-service',
69
+ 'srv/cardano-sign-service',
70
+ 'srv/cardano-indexer-service',
71
+ 'srv/cardano-worker-service',
72
+ 'srv/cardano-agent-service'
73
+ ];
55
74
  cds_1.default.env.requires.kinds['odatano-core'] = {
56
75
  impl: '@odatano/core',
57
- model: [
58
- '@odatano/core/db/schema',
59
- '@odatano/core/srv/cardano-service',
60
- '@odatano/core/srv/cardano-tx-service',
61
- '@odatano/core/srv/cardano-sign-service',
62
- '@odatano/core/srv/cardano-indexer-service',
63
- '@odatano/core/srv/cardano-worker-service'
64
- ]
76
+ model: [...PLUGIN_MODEL]
65
77
  };
66
78
  // CRITICAL: Also set model directly on the requires entry.
67
79
  // CAP's _link_required_services() merges kind→requires BEFORE cds-plugin.js runs,
68
80
  // so the model array on the kind is never merged. Set it directly.
69
81
  const req = cds_1.default.env.requires['odatano-core'];
70
82
  if (req) {
71
- req.model = [
72
- '@odatano/core/db/schema',
73
- '@odatano/core/srv/cardano-service',
74
- '@odatano/core/srv/cardano-tx-service',
75
- '@odatano/core/srv/cardano-sign-service',
76
- '@odatano/core/srv/cardano-indexer-service',
77
- '@odatano/core/srv/cardano-worker-service'
78
- ];
83
+ req.model = [...PLUGIN_MODEL];
79
84
  }
80
85
  logger.debug('Plugin registered');
86
+ /**
87
+ * Agent grants (AGENT_GRANTS_DESIGN.md). Off by default; switched on by
88
+ * cds.requires.odatano-core.agentGrants.enabled / AGENT_GRANTS_ENABLED=true.
89
+ * Has to run at plugin load, before CAP builds its middlewares (the auth impl
90
+ * is swapped here). srv/server.ts makes the same call for standalone mode, where
91
+ * this file is never loaded; the call is idempotent and never throws.
92
+ */
93
+ require('../srv/utils/agent-grants-config')
94
+ .activateAgentGrants();
81
95
  /**
82
96
  * Rewrite @impl paths for plugin mode.
83
97
  * CDS files use relative @impl (e.g. 'srv/cardano-service') which resolves from cds.root.
@@ -90,20 +104,9 @@ cds_1.default.on('loaded', (model) => {
90
104
  return;
91
105
  const defs = model.definitions ?? {};
92
106
  for (const def of Object.values(defs)) {
93
- if (def['@impl'] === 'srv/cardano-service') {
94
- def['@impl'] = '@odatano/core/srv/cardano-service';
95
- }
96
- else if (def['@impl'] === 'srv/cardano-tx-service') {
97
- def['@impl'] = '@odatano/core/srv/cardano-tx-service';
98
- }
99
- else if (def['@impl'] === 'srv/cardano-sign-service') {
100
- def['@impl'] = '@odatano/core/srv/cardano-sign-service';
101
- }
102
- else if (def['@impl'] === 'srv/cardano-indexer-service') {
103
- def['@impl'] = '@odatano/core/srv/cardano-indexer-service';
104
- }
105
- else if (def['@impl'] === 'srv/cardano-worker-service') {
106
- def['@impl'] = '@odatano/core/srv/cardano-worker-service';
107
+ const impl = def['@impl'];
108
+ if (impl && IMPL_PATHS.includes(impl)) {
109
+ def['@impl'] = `@odatano/core/${impl}`;
107
110
  }
108
111
  }
109
112
  });
@@ -1,6 +1,16 @@
1
1
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
2
2
  import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint } from './cardano-backend';
3
3
  import { Network } from '../cardano-client';
4
+ /**
5
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
6
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
7
+ * 0x3 = script hash. The validators already enforce HRP + length before the
8
+ * request reaches a backend, so this only has to split the payload.
9
+ */
10
+ export declare function decodeDrepId(drepId: string): {
11
+ hashHex: string;
12
+ isScript: boolean;
13
+ };
4
14
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
5
15
  export declare function resolveOgmiosTip(tip: 'origin' | {
6
16
  slot: number;
@@ -107,11 +117,21 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
107
117
  */
108
118
  getTransactionMetadata(_tx_hash: string): Promise<MetadataLabelTx[]>;
109
119
  /**
110
- * Get specific Drep Data (not supported for Ogmios)
111
- * @param _drepId drep id
120
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
121
+ *
122
+ * The client package (6.14) ships the schema types but no wrapper for this query,
123
+ * so it goes through the exported `Method()` primitive on our interaction context —
124
+ * the same building block the client uses for `stakePools` & co.
125
+ *
126
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
127
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
128
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
129
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
130
+ *
131
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
112
132
  * @returns {Promise<DrepData>} drep data
113
133
  */
114
- getDrep(_drepId: string): Promise<DrepData>;
134
+ getDrep(drepId: string): Promise<DrepData>;
115
135
  /**
116
136
  * Get Asset Info (not supported for Ogmios — no aggregate-supply query in the protocol)
117
137
  * @param _unit asset unit (policyId + assetNameHex)
@@ -4,11 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.OgmiosBackend = void 0;
7
+ exports.decodeDrepId = decodeDrepId;
7
8
  exports.resolveOgmiosTip = resolveOgmiosTip;
8
9
  exports.resolveOgmiosHeight = resolveOgmiosHeight;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
10
11
  const node_http_1 = __importDefault(require("node:http"));
11
12
  const client_1 = require("@cardano-ogmios/client");
13
+ const bech32_1 = require("bech32");
12
14
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
13
15
  const errors_1 = require("../../utils/errors");
14
16
  const mappers_1 = require("../../utils/mappers");
@@ -63,6 +65,23 @@ function ogmiosValueToLovelaceString(value) {
63
65
  const lovelace = value.ada?.lovelace;
64
66
  return lovelace === undefined ? '0' : String(lovelace);
65
67
  }
68
+ /**
69
+ * Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into its credential hash and
70
+ * type. Header byte: high nibble 0x2 = DRep, low nibble 0x2 = key hash /
71
+ * 0x3 = script hash. The validators already enforce HRP + length before the
72
+ * request reaches a backend, so this only has to split the payload.
73
+ */
74
+ function decodeDrepId(drepId) {
75
+ const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
76
+ const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
77
+ if (decoded.prefix !== 'drep' || bytes.length !== 29) {
78
+ throw new errors_1.NotFoundError('Drep', 'ogmios');
79
+ }
80
+ return {
81
+ hashHex: bytes.subarray(1).toString('hex'),
82
+ isScript: (bytes[0] & 0x0f) === 0x03,
83
+ };
84
+ }
66
85
  /** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
67
86
  function resolveOgmiosTip(tip) {
68
87
  return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
@@ -88,7 +107,8 @@ class OgmiosBackend {
88
107
  'getTransaction',
89
108
  'getTransactionMetadata',
90
109
  'getAddressTransactions',
91
- 'getDrep',
110
+ // getDrep is NOT listed: served from the live ledger state via
111
+ // queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
92
112
  'getAssetInfo',
93
113
  'getAddress',
94
114
  'getNetworkInformation',
@@ -305,13 +325,60 @@ class OgmiosBackend {
305
325
  }, this.name);
306
326
  }
307
327
  /**
308
- * Get specific Drep Data (not supported for Ogmios)
309
- * @param _drepId drep id
328
+ * Get DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`).
329
+ *
330
+ * The client package (6.14) ships the schema types but no wrapper for this query,
331
+ * so it goes through the exported `Method()` primitive on our interaction context —
332
+ * the same building block the client uses for `stakePools` & co.
333
+ *
334
+ * Semantics vs. Blockfrost/Koios: Ogmios only lists REGISTERED DReps, so a retired
335
+ * or unknown DRep is a NotFoundError here (never `retired: true`), and there is no
336
+ * last-activity epoch — `expired` is derived from the mandate epoch instead.
337
+ * Routing keeps `getDrep` historical-preferred; this is the Ogmios-only fallback.
338
+ *
339
+ * @param drepId CIP-129 bech32 DRep ID (`drep1…`)
310
340
  * @returns {Promise<DrepData>} drep data
311
341
  */
312
- async getDrep(_drepId) {
342
+ async getDrep(drepId) {
313
343
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
314
- throw new errors_1.ProviderUnavailableError('DRep queries not supported by Ogmios backend', this.name);
344
+ await this.ensureConnected();
345
+ if (!this.context) {
346
+ throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
347
+ }
348
+ const { hashHex, isScript } = decodeDrepId(drepId);
349
+ const [summaries, currentEpoch] = await Promise.all([
350
+ (0, client_1.Method)({
351
+ method: 'queryLedgerState/delegateRepresentatives',
352
+ params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
353
+ }, {
354
+ handler: (response, resolve, reject) => {
355
+ if (response.error) {
356
+ reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
357
+ }
358
+ else {
359
+ resolve(Array.isArray(response.result) ? response.result : []);
360
+ }
361
+ },
362
+ }, this.context),
363
+ this.stateQueryClient.epoch(),
364
+ ]);
365
+ // Filter by id: the query is already credential-scoped, but never trust a
366
+ // broader answer (abstain/noConfidence rows carry no id and are dropped here).
367
+ const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
368
+ if (!drep)
369
+ throw new errors_1.NotFoundError('Drep', this.name);
370
+ const mandateEpoch = drep.mandate?.epoch;
371
+ return {
372
+ drepId,
373
+ hex: hashHex,
374
+ amount: ogmiosValueToLovelaceString(drep.stake),
375
+ hasScript: isScript || drep.from === 'script',
376
+ // Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0,
377
+ // matching what the Koios mapper does since its schema change.
378
+ lastActiveEpoch: 0,
379
+ expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
380
+ retired: false,
381
+ };
315
382
  }, this.name);
316
383
  }
317
384
  /**
@@ -28,6 +28,13 @@ export interface TrackedJob {
28
28
  submittedAt: string;
29
29
  foundSlot: number | null;
30
30
  foundHeight: number | null;
31
+ /**
32
+ * Polling round in which the tx was last SEEN on-chain (found or
33
+ * re-validated). A job found in the current round needs no second lookup
34
+ * before it is confirmed; one found in an earlier round is re-checked, so a
35
+ * rollback the crawler did not report (crawler off) cannot slip through.
36
+ */
37
+ seenRound?: number;
31
38
  }
32
39
  export interface ConfirmationTrackerOptions {
33
40
  confirmationDepth: number;
@@ -59,6 +66,8 @@ export declare class ConfirmationTracker {
59
66
  private running;
60
67
  private polling;
61
68
  private lastKnownTipHeight;
69
+ /** Polling round counter; see TrackedJob.seenRound. */
70
+ private round;
62
71
  constructor(deps: ConfirmationTrackerDeps);
63
72
  start(): void;
64
73
  stop(): void;
@@ -77,10 +86,32 @@ export declare class ConfirmationTracker {
77
86
  }): void;
78
87
  private onBlockIndexed;
79
88
  private onReorg;
89
+ /**
90
+ * The recorded inclusion is gone (a reorg the crawler reported, or a polling
91
+ * re-check that no longer finds the tx): back to watching, and optionally
92
+ * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
93
+ * guard. "Already known" means the tx survived into the new chain's mempool;
94
+ * that is success, not an error.
95
+ */
96
+ private forgetInclusion;
80
97
  /** One polling round. Public for tests; guarded against overlapping rounds. */
81
98
  pollOnce(): Promise<void>;
82
- /** Confirm every found job whose depth requirement is met by the known tip. */
99
+ /**
100
+ * Confirm every found job whose depth requirement is met by the known tip.
101
+ * `revalidate` (polling path): an inclusion not seen in THIS round is looked
102
+ * up again first — the crawler's reorg events are the only rollback signal,
103
+ * and with the crawler off there is none, so a tx that was found at height N
104
+ * and then rolled back would otherwise be confirmed on the tip alone.
105
+ */
83
106
  private confirmMature;
107
+ /**
108
+ * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
109
+ * moved to another block (re-included after a rollback) gets its new point
110
+ * and is judged at the new height; one that is gone is forgotten (back to
111
+ * watching, optional same-CBOR re-submit) and the tip is re-learned next
112
+ * round, because the pre-rollback tip may overstate the depth.
113
+ */
114
+ private stillIncluded;
84
115
  private finalize;
85
116
  }
86
117
  //# sourceMappingURL=confirmation-tracker.d.ts.map
@@ -18,6 +18,8 @@ class ConfirmationTracker {
18
18
  running = false;
19
19
  polling = false;
20
20
  lastKnownTipHeight = null;
21
+ /** Polling round counter; see TrackedJob.seenRound. */
22
+ round = 0;
21
23
  constructor(deps) {
22
24
  this.deps = deps;
23
25
  }
@@ -103,29 +105,38 @@ class ConfirmationTracker {
103
105
  for (const job of this.pending.values()) {
104
106
  if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
105
107
  logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
106
- job.foundSlot = null;
107
- job.foundHeight = null;
108
- try {
109
- await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
110
- }
111
- catch (err) {
112
- logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
108
+ await this.forgetInclusion(job);
109
+ }
110
+ }
111
+ }
112
+ /**
113
+ * The recorded inclusion is gone (a reorg the crawler reported, or a polling
114
+ * re-check that no longer finds the tx): back to watching, and optionally
115
+ * re-submit the SAME signed CBOR — never a rebuild, that is the double-spend
116
+ * guard. "Already known" means the tx survived into the new chain's mempool;
117
+ * that is success, not an error.
118
+ */
119
+ async forgetInclusion(job) {
120
+ job.foundSlot = null;
121
+ job.foundHeight = null;
122
+ job.seenRound = undefined;
123
+ try {
124
+ await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
125
+ }
126
+ catch (err) {
127
+ logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
128
+ }
129
+ if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
130
+ try {
131
+ await this.deps.client.submitTransaction(job.signedTxCbor);
132
+ logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
133
+ }
134
+ catch (err) {
135
+ if (err instanceof errors_1.TransactionAlreadySubmittedError) {
136
+ logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
113
137
  }
114
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
115
- // SAME signed CBOR only — never a rebuild. "Already known" means the tx
116
- // survived into the new chain's mempool; that is success, not an error.
117
- try {
118
- await this.deps.client.submitTransaction(job.signedTxCbor);
119
- logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
120
- }
121
- catch (err) {
122
- if (err instanceof errors_1.TransactionAlreadySubmittedError) {
123
- logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
124
- }
125
- else {
126
- logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
127
- }
128
- }
138
+ else {
139
+ logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
129
140
  }
130
141
  }
131
142
  }
@@ -136,6 +147,7 @@ class ConfirmationTracker {
136
147
  if (!this.running || this.polling || this.pending.size === 0)
137
148
  return;
138
149
  this.polling = true;
150
+ this.round++;
139
151
  try {
140
152
  // Tip first — also serves the depth check for hook-found entries when the
141
153
  // crawler is off.
@@ -156,6 +168,7 @@ class ConfirmationTracker {
156
168
  const tx = await this.deps.client.getTransaction(job.txHash);
157
169
  job.foundSlot = tx.slot ?? null;
158
170
  job.foundHeight = tx.blockHeight ?? null;
171
+ job.seenRound = this.round;
159
172
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
160
173
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
161
174
  }
@@ -175,31 +188,73 @@ class ConfirmationTracker {
175
188
  }
176
189
  }
177
190
  }
178
- await this.confirmMature();
191
+ // Polling has no reorg signal, so an inclusion recorded in an EARLIER
192
+ // round is re-checked before it counts (see stillIncluded).
193
+ await this.confirmMature(true);
179
194
  }
180
195
  finally {
181
196
  this.polling = false;
182
197
  }
183
198
  }
184
199
  // ---- Shared -----------------------------------------------------------------
185
- /** Confirm every found job whose depth requirement is met by the known tip. */
186
- async confirmMature() {
200
+ /**
201
+ * Confirm every found job whose depth requirement is met by the known tip.
202
+ * `revalidate` (polling path): an inclusion not seen in THIS round is looked
203
+ * up again first — the crawler's reorg events are the only rollback signal,
204
+ * and with the crawler off there is none, so a tx that was found at height N
205
+ * and then rolled back would otherwise be confirmed on the tip alone.
206
+ */
207
+ async confirmMature(revalidate = false) {
187
208
  const tip = this.lastKnownTipHeight;
188
209
  if (tip == null)
189
210
  return;
190
211
  for (const job of [...this.pending.values()]) {
191
212
  if (job.foundHeight == null)
192
213
  continue;
193
- const confirmations = tip - job.foundHeight + 1;
194
- if (confirmations >= this.deps.options.confirmationDepth) {
195
- await this.finalize(job, 'confirmed');
214
+ if (tip - job.foundHeight + 1 < this.deps.options.confirmationDepth)
215
+ continue;
216
+ if (revalidate && job.seenRound !== this.round && !(await this.stillIncluded(job, tip)))
217
+ continue;
218
+ await this.finalize(job, 'confirmed');
219
+ }
220
+ }
221
+ /**
222
+ * Is the tx still on-chain, and still deep enough? Re-reads it; a tx that
223
+ * moved to another block (re-included after a rollback) gets its new point
224
+ * and is judged at the new height; one that is gone is forgotten (back to
225
+ * watching, optional same-CBOR re-submit) and the tip is re-learned next
226
+ * round, because the pre-rollback tip may overstate the depth.
227
+ */
228
+ async stillIncluded(job, tip) {
229
+ try {
230
+ const tx = await this.deps.client.getTransaction(job.txHash);
231
+ const height = tx.blockHeight ?? null;
232
+ job.seenRound = this.round;
233
+ if (height != null && height !== job.foundHeight) {
234
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height} — re-anchoring`);
235
+ job.foundHeight = height;
236
+ job.foundSlot = tx.slot ?? null;
237
+ await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
238
+ return tip - height + 1 >= this.deps.options.confirmationDepth;
239
+ }
240
+ return true;
241
+ }
242
+ catch (err) {
243
+ if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
244
+ logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}) — rollback without a crawler signal, re-watching`);
245
+ this.lastKnownTipHeight = null;
246
+ await this.forgetInclusion(job);
247
+ return false;
196
248
  }
249
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
250
+ return false;
197
251
  }
198
252
  }
199
253
  async finalize(job, outcome, errorCode, err) {
254
+ let transitioned = false;
200
255
  try {
201
256
  await cds_1.default.tx(async (tx) => {
202
- const transitioned = outcome === 'confirmed'
257
+ transitioned = outcome === 'confirmed'
203
258
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
204
259
  : await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
205
260
  if (transitioned) {
@@ -212,6 +267,13 @@ class ConfirmationTracker {
212
267
  return; // keep tracking — the next poll round retries the transition
213
268
  }
214
269
  this.pending.delete(job.jobId);
270
+ if (!transitioned) {
271
+ // Somebody else (another tracker instance, a reconciliation pass, a
272
+ // cancel) reached the terminal state first. The job is done either way,
273
+ // but the stats bump and the terminal event belong to the winner only.
274
+ logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere — no event from this tracker`);
275
+ return;
276
+ }
215
277
  logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
216
278
  this.deps.onFinal?.({
217
279
  jobId: job.jobId,
@@ -103,6 +103,17 @@ export interface InsertJobResult {
103
103
  /** True when an idempotent retry matched an existing non-failed job. */
104
104
  deduplicated: boolean;
105
105
  }
106
+ /** The job that currently owns an idempotency key, or null when it is free. */
107
+ /**
108
+ * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
109
+ * submits. Two agents (two grants, two users) may both use `order-1` on the
110
+ * same wallet: each must get its own job, never a "deduplicated" answer that
111
+ * hands one the other's job id. A key from an owner-less caller (privileged
112
+ * test context) stays as-is; an owned key becomes a hash of owner + key, which
113
+ * fits the String(100) column whatever the owner id's length and never collides
114
+ * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
115
+ */
116
+ export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
106
117
  /**
107
118
  * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
108
119
  * docs). Idempotency: an active-or-successful row with the same (walletId, kind,