@odatano/core 2.0.0-rc.45 → 2.0.0-rc.46

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/README.md CHANGED
@@ -35,31 +35,31 @@ npm install @odatano/core @cap-js/sqlite
35
35
  "db": { "kind": "sqlite" },
36
36
  "odatano-core": {
37
37
  "network": "preview",
38
- "backends": ["blockfrost"]
38
+ "backends": ["koios"]
39
39
  }
40
40
  }
41
41
  }
42
42
  }
43
43
  ```
44
44
 
45
- Put your API key in a `.env` file in the project root (loaded automatically by `cds serve` / `cds watch`) — don't commit it to `package.json`:
46
-
47
45
  ```bash
48
- # .env
49
- BLOCKFROST_API_KEY=preview_your_api_key_here
46
+ cds deploy --to sqlite
47
+ cds serve
50
48
  ```
51
49
 
50
+ Koios works without an account on its public tier. A [Koios token](https://koios.rest) is optional and raises the rate limit. Put it in a `.env` file in the project root (loaded automatically by `cds serve` / `cds watch`), not in `package.json`:
51
+
52
52
  ```bash
53
- cds deploy --to sqlite
54
- cds serve
53
+ # .env (optional)
54
+ KOIOS_API_KEY=your_koios_token
55
55
  ```
56
56
 
57
57
  > Config in `cds.requires.odatano-core` takes precedence over environment
58
- > variables; a `blockfrostApiKey` set there would override the `.env` value.
58
+ > variables; a `koiosApiKey` set there would override the `.env` value.
59
59
 
60
- > **Self-hosted Blockfrost-compatible node?** (Dolos MiniBF, Demeter Self-Hosted)
61
- > Set `blockfrostCustomBackend` to the node's base URL (e.g. `http://localhost:3010/api/v0`).
62
- > When set, `blockfrostApiKey` becomes optional. See the [Backend Configuration Guide](docs/guides/BACKEND_CONFIGURATION.md#self-hosted-blockfrost-compatible-backends).
60
+ Other backends are optional and can be combined, for example `["ogmios", "koios"]` with a local node, or
61
+ `blockfrost` with a Blockfrost key or a self-hosted Blockfrost-compatible node. See the
62
+ [Backend Configuration Guide](docs/guides/BACKEND_CONFIGURATION.md).
63
63
 
64
64
  ### Standalone
65
65
 
@@ -68,7 +68,7 @@ Run ODATANO as a self-contained service (no host CAP project needed):
68
68
  ```bash
69
69
  git clone https://github.com/ODATANO/ODATANO && cd ODATANO
70
70
  npm ci
71
- cp .env.example .env # set BLOCKFROST_API_KEY, NETWORK, BACKENDS
71
+ cp .env.example .env # set NETWORK, BACKENDS (default koios), optional KOIOS_API_KEY
72
72
  cds deploy --to sqlite
73
73
  cds serve
74
74
  ```
@@ -83,8 +83,8 @@ docker compose logs -f ogmios # watch sync (/health: 202 syncing, 20
83
83
  ```
84
84
 
85
85
  > First sync from genesis takes hours; the node DB persists in a Docker volume so
86
- > restarts resume. Until Ogmios catches up, historical queries fall back to
87
- > Blockfrost (set `BLOCKFROST_API_KEY`).
86
+ > restarts resume. Until Ogmios catches up, queries fall back to Koios
87
+ > (optional `KOIOS_API_KEY`).
88
88
 
89
89
  Service available at `http://localhost:4004`. See the [Quick Start Guide](docs/QUICK_START.md#local-ogmios--cardano-node-docker) for the local Ogmios stack and full details.
90
90
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/core",
3
- "version": "2.0.0-rc.45",
3
+ "version": "2.0.0-rc.46",
4
4
  "description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
5
5
  "imports": {
6
6
  "#cds-models/*": "./@cds-models/*/index.js"
@@ -514,9 +514,10 @@ class KoiosBackend {
514
514
  blockHeight: null,
515
515
  };
516
516
  });
517
- // Koios may return ascending order
518
- events.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
519
- return events.slice(0, Math.max(1, limit));
517
+ // Koios may return ascending order and may list one transaction twice
518
+ const unique = [...new Map(events.map(e => [e.txHash, e])).values()];
519
+ unique.sort((a, b) => (b.blockTime ?? 0) - (a.blockTime ?? 0));
520
+ return unique.slice(0, Math.max(1, limit));
520
521
  }, this.name);
521
522
  }
522
523
  async getDrep(drepId) {
@@ -141,6 +141,12 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
141
141
  getPool(poolId: string): Promise<PoolData>;
142
142
  getAccount(stakeAddress: string): Promise<AccountData>;
143
143
  submitTransaction(signedTxCbor: string): Promise<string>;
144
+ /** Hash of a signed transaction, or null when the CBOR does not parse. */
145
+ private txHashOrNull;
146
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. */
147
+ private isKnownTransaction;
148
+ /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
149
+ private mempoolHas;
144
150
  evaluateTransaction(unsignedTxCbor: string): Promise<ScriptEvaluationResult[]>;
145
151
  getProtocolParameters(): Promise<LedgerProtocolParameters>;
146
152
  getLatestEpoch(): Promise<EpochData>;
@@ -19,11 +19,14 @@ const crypto_1 = require("@harmoniclabs/crypto");
19
19
  const reference_script_1 = require("../../utils/reference-script");
20
20
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
21
21
  const errors_1 = require("../../utils/errors");
22
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
22
23
  const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
23
24
  const epoch_slots_1 = require("../../utils/epoch-slots");
24
25
  const mappers_1 = require("../../utils/mappers");
25
26
  const const_1 = require("../../utils/const");
26
27
  const logger = cds_1.default.log('OgmiosBackend');
28
+ /** Node rejection text for inputs that are no longer unspent. */
29
+ const SPENT_INPUTS = /inputs are spent|unknown output reference|already been included/i;
27
30
  /** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
28
31
  function parseOgmiosRatio(ratio) {
29
32
  if (ratio === null || ratio === undefined)
@@ -647,12 +650,57 @@ class OgmiosBackend {
647
650
  const e = err;
648
651
  if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
649
652
  const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
653
+ // spent inputs are also what a resubmit of a transaction the node already holds reports
654
+ if (SPENT_INPUTS.test(`${String(e.message ?? '')}${detail}`)) {
655
+ const txHash = this.txHashOrNull(signedTxCbor);
656
+ if (txHash && await this.isKnownTransaction(txHash))
657
+ throw new errors_1.TransactionAlreadySubmittedError(txHash, err);
658
+ }
650
659
  throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
651
660
  }
652
661
  throw err;
653
662
  }
654
663
  }, this.name);
655
664
  }
665
+ /** Hash of a signed transaction, or null when the CBOR does not parse. */
666
+ txHashOrNull(signedTxCbor) {
667
+ try {
668
+ return (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
669
+ }
670
+ catch {
671
+ return null;
672
+ }
673
+ }
674
+ /** Whether the node holds the transaction: in its mempool, or on chain with its first output unspent. */
675
+ async isKnownTransaction(txHash) {
676
+ try {
677
+ if (await this.mempoolHas(txHash))
678
+ return true;
679
+ const query = await this.scanQueryClient();
680
+ const onChain = await this.withInitTimeout(query.utxo({ outputReferences: [{ transaction: { id: txHash }, index: 0 }] }), 'utxo/known-transaction');
681
+ return onChain.length > 0;
682
+ }
683
+ catch (err) {
684
+ logger.warn(`[OgmiosBackend] could not check whether ${txHash} is known: ${err instanceof Error ? err.message : String(err)}`);
685
+ return false;
686
+ }
687
+ }
688
+ /** Mempool lookup on its own short connection, since an acquired mempool snapshot blocks the session. */
689
+ async mempoolHas(txHash) {
690
+ const url = new URL(this.ogmiosUrl);
691
+ const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
692
+ const context = await this.withInitTimeout((0, client_1.createInteractionContext)((err) => logger.debug(`[OgmiosBackend] mempool context error: ${err.message}`), () => undefined, { connection }), 'mempool/createInteractionContext');
693
+ try {
694
+ const mempool = await this.withInitTimeout((0, client_1.createMempoolMonitoringClient)(context), 'mempool/client');
695
+ await this.withInitTimeout(mempool.acquireMempool(), 'mempool/acquire');
696
+ const has = await this.withInitTimeout(mempool.hasTransaction(txHash), 'mempool/hasTransaction');
697
+ await mempool.shutdown().catch(() => undefined);
698
+ return has;
699
+ }
700
+ finally {
701
+ this.forceCloseContext(context);
702
+ }
703
+ }
656
704
  async evaluateTransaction(unsignedTxCbor) {
657
705
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
658
706
  await this.ensureConnected();
@@ -195,6 +195,8 @@ export declare class CardanoIndexer {
195
195
  }): Promise<TransactionSubmission>;
196
196
  /** Update a submission's status (two-phase submit: pending → submitted or failed). */
197
197
  updateSubmissionStatus(tx: CapTransaction, submissionId: string, status: TransactionSubmission['status'], errorMessage?: string): Promise<void>;
198
+ /** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
199
+ dropDuplicateSubmission(tx: CapTransaction, submissionId: string, txHash: string): Promise<boolean>;
198
200
  /** Persist a new signing request and link it to the build's sender address. */
199
201
  persistSigningRequest(tx: CapTransaction, params: {
200
202
  buildId: string;
@@ -1596,6 +1596,16 @@ class CardanoIndexer {
1596
1596
  .where({ id: submissionId }));
1597
1597
  logger.debug({ submissionId, status }, 'Updated submission status');
1598
1598
  }
1599
+ /** Deletes a resubmit's row when the transaction already has a submitted or confirmed row. */
1600
+ async dropDuplicateSubmission(tx, submissionId, txHash) {
1601
+ const existing = await tx.run(SELECT.one.from(CardanoTransactionService_1.TransactionSubmissions).columns('id')
1602
+ .where({ txHash, status: { in: ['submitted', 'confirmed'] }, id: { '!=': submissionId } }));
1603
+ if (!existing)
1604
+ return false;
1605
+ await tx.run(DELETE.from(CardanoTransactionService_1.TransactionSubmissions).where({ id: submissionId }));
1606
+ logger.debug({ submissionId, existingId: existing.id, txHash }, 'Dropped duplicate submission row');
1607
+ return true;
1608
+ }
1599
1609
  /** Persist a new signing request and link it to the build's sender address. */
1600
1610
  async persistSigningRequest(tx, params) {
1601
1611
  const { buildId, signingPayload } = params;
@@ -17,7 +17,7 @@ export interface FinalizeParams {
17
17
  signerType?: string;
18
18
  signerInfo?: string;
19
19
  }
20
- type SubmissionIndexer = Pick<CardanoIndexer, 'persistTransactionSubmission' | 'updateSubmissionStatus' | 'invalidateUtxoCacheForTx'>;
20
+ type SubmissionIndexer = Pick<CardanoIndexer, 'persistTransactionSubmission' | 'updateSubmissionStatus' | 'dropDuplicateSubmission' | 'invalidateUtxoCacheForTx'>;
21
21
  export declare function submitAndFinalize(SigningRequests: unknown, params: FinalizeParams, afterFinalize?: (db: cds.Transaction) => Promise<void>): Promise<unknown>;
22
22
  export declare function submitRecorded(params: {
23
23
  signedTxCbor: string;
@@ -69,9 +69,14 @@ async function submitRecorded(params, indexer = server().getCardanoIndexer(), cl
69
69
  const alreadySubmitted = submitErr instanceof errors_1.TransactionAlreadySubmittedError;
70
70
  const errMsg = submitErr instanceof Error ? submitErr.message : String(submitErr);
71
71
  try {
72
- await (0, tx_utils_1.detachedTx)('record submission outcome', (db) => alreadySubmitted
73
- ? indexer.updateSubmissionStatus(db, record.id, 'submitted')
74
- : indexer.updateSubmissionStatus(db, record.id, 'failed', errMsg));
72
+ // A resubmit keeps one row per transaction: its own row goes when an earlier one exists.
73
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
74
+ if (!alreadySubmitted)
75
+ return indexer.updateSubmissionStatus(db, record.id, 'failed', errMsg);
76
+ if (await indexer.dropDuplicateSubmission(db, record.id, params.txHash))
77
+ return;
78
+ return indexer.updateSubmissionStatus(db, record.id, 'submitted');
79
+ });
75
80
  }
76
81
  catch (markErr) {
77
82
  logger.error({ err: markErr, submissionId: record.id }, 'Could not record the submission outcome after a submit error');