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

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.47",
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');
@@ -6,7 +6,7 @@ export interface Rational {
6
6
  den: bigint;
7
7
  }
8
8
  export declare function tierRefScriptFee(totalBytes: bigint, pricePerByte: Rational): bigint;
9
- /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
9
+ /** Reference-script bytes of the inputs and reference inputs as one set. A UTxO in both counts once, the same script on two UTxOs twice. */
10
10
  export declare function refScriptBytesOf(tx: Tx): bigint;
11
11
  /** Replace `TxBuilder.prototype.calcMinFee` once per process. */
12
12
  export declare function installReferenceScriptFeePatch(): void;
@@ -31,10 +31,12 @@ function tierRefScriptFee(totalBytes, pricePerByte) {
31
31
  add(remaining);
32
32
  return accNum / accDen;
33
33
  }
34
- /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
34
+ /** Reference-script bytes of the inputs and reference inputs as one set. A UTxO in both counts once, the same script on two UTxOs twice. */
35
35
  function refScriptBytesOf(tx) {
36
- const utxos = [...tx.body.inputs, ...(tx.body.refInputs ?? [])];
37
- return utxos.reduce((sum, u) => sum + BigInt(u.resolved.refScript ? (0, reference_script_1.referenceScriptSize)(u.resolved.refScript) : 0), 0n);
36
+ const utxos = new Map();
37
+ for (const u of [...tx.body.inputs, ...(tx.body.refInputs ?? [])])
38
+ utxos.set(u.utxoRef.toString(), u);
39
+ return [...utxos.values()].reduce((sum, u) => sum + BigInt(u.resolved.refScript ? (0, reference_script_1.referenceScriptSize)(u.resolved.refScript) : 0), 0n);
38
40
  }
39
41
  function refScriptPrice(pp) {
40
42
  const r = (0, cardano_ledger_ts_1.cborFromRational)(pp.minfeeRefScriptCostPerByte ?? cardano_ledger_ts_1.defaultProtocolParameters.minfeeRefScriptCostPerByte);
@@ -19,6 +19,7 @@ const plutus_data_1 = require("@harmoniclabs/plutus-data");
19
19
  const caller_datums_1 = require("./caller-datums");
20
20
  const const_1 = require("../../utils/const");
21
21
  const buildooor_fee_patch_1 = require("./buildooor-fee-patch");
22
+ const redeemer_tag_patch_1 = require("../../cbor/redeemer-tag-patch");
22
23
  const reference_script_1 = require("../../utils/reference-script");
23
24
  const logger = cds_1.default.log('BuildooorTxBuilder');
24
25
  /**
@@ -116,6 +117,7 @@ if (!Object.prototype.hasOwnProperty.call(cardano_ledger_ts_1.Hash32.prototype,
116
117
  cardano_ledger_ts_1.Hash32.prototype.clone = function () { return new cardano_ledger_ts_1.Hash32(this.toString()); };
117
118
  }
118
119
  (0, buildooor_fee_patch_1.installReferenceScriptFeePatch)();
120
+ (0, redeemer_tag_patch_1.installRedeemerTagPatch)();
119
121
  /** CardanoTxBuilder implementation on top of Buildooor. */
120
122
  class BuildooorTxBuilder {
121
123
  name = 'BuildooorTxBuilder';
package/srv/cbor/parse.js CHANGED
@@ -6,6 +6,8 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
6
  const cbor_1 = require("@harmoniclabs/cbor");
7
7
  const errors_1 = require("../utils/errors");
8
8
  const error_codes_1 = require("../utils/error-codes");
9
+ const redeemer_tag_patch_1 = require("./redeemer-tag-patch");
10
+ (0, redeemer_tag_patch_1.installRedeemerTagPatch)();
9
11
  // Pure, no network call. Callers validate size and format with `isValidTxCborHex` first.
10
12
  // Throws TX_PARSE_FAILED on malformed CBOR.
11
13
  function parseTransaction(cborHex) {
@@ -0,0 +1,3 @@
1
+ /** Let `TxRedeemer` decode and clone Voting and Proposing redeemers. Once per process. */
2
+ export declare function installRedeemerTagPatch(): void;
3
+ //# sourceMappingURL=redeemer-tag-patch.d.ts.map
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installRedeemerTagPatch = installRedeemerTagPatch;
4
+ const cbor_1 = require("@harmoniclabs/cbor");
5
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
6
+ // The TxRedeemer constructor accepts only tags 0 to 3, so Tx.fromCbor throws on Conway voting and
7
+ // proposing redeemers. Decode and clone them with tag 0, then set the real tag.
8
+ const CONWAY_TAGS = new Set([cardano_ledger_ts_1.TxRedeemerTag.Voting, cardano_ledger_ts_1.TxRedeemerTag.Proposing]);
9
+ const PLACEHOLDER = new cbor_1.CborUInt(cardano_ledger_ts_1.TxRedeemerTag.Spend);
10
+ function conwayTag(head) {
11
+ const first = head.array[0];
12
+ if (!(first instanceof cbor_1.CborUInt))
13
+ return undefined;
14
+ const tag = Number(first.num);
15
+ return CONWAY_TAGS.has(tag) ? tag : undefined;
16
+ }
17
+ // Swaps the tag in the parsed CBOR for the call only. The CBOR object keeps its byte reference.
18
+ function decodeWithPlaceholder(head, decode) {
19
+ const tag = conwayTag(head);
20
+ if (tag === undefined)
21
+ return decode();
22
+ const original = head.array[0];
23
+ head.array[0] = PLACEHOLDER;
24
+ try {
25
+ const redeemer = decode();
26
+ redeemer.tag = tag;
27
+ return redeemer;
28
+ }
29
+ finally {
30
+ head.array[0] = original;
31
+ }
32
+ }
33
+ const PATCHED = Symbol.for('odatano.ledger-ts.redeemerTags');
34
+ /** Let `TxRedeemer` decode and clone Voting and Proposing redeemers. Once per process. */
35
+ function installRedeemerTagPatch() {
36
+ const cls = cardano_ledger_ts_1.TxRedeemer;
37
+ if (cls[PATCHED])
38
+ return;
39
+ const fromCborObj = cls.fromCborObj;
40
+ const fromCborMapEntry = cls.fromCborMapEntry;
41
+ const clone = cardano_ledger_ts_1.TxRedeemer.prototype.clone;
42
+ cls.fromCborObj = (cObj) => cObj instanceof cbor_1.CborArray ? decodeWithPlaceholder(cObj, () => fromCborObj(cObj)) : fromCborObj(cObj);
43
+ cls.fromCborMapEntry = (entry) => entry?.k instanceof cbor_1.CborArray ? decodeWithPlaceholder(entry.k, () => fromCborMapEntry(entry)) : fromCborMapEntry(entry);
44
+ cardano_ledger_ts_1.TxRedeemer.prototype.clone = function () {
45
+ const self = this;
46
+ const tag = self.tag;
47
+ if (!CONWAY_TAGS.has(tag))
48
+ return clone.call(this);
49
+ self.tag = cardano_ledger_ts_1.TxRedeemerTag.Spend;
50
+ try {
51
+ const copy = clone.call(this);
52
+ copy.tag = tag;
53
+ return copy;
54
+ }
55
+ finally {
56
+ self.tag = tag;
57
+ }
58
+ };
59
+ cls[PATCHED] = true;
60
+ }
61
+ //# sourceMappingURL=redeemer-tag-patch.js.map