@odatano/core 2.0.0-rc.1 → 2.0.0-rc.10

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 (61) 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 +37 -2
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  7. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  8. package/@cds-models/odatano/cardano/index.js +6 -0
  9. package/README.md +62 -4
  10. package/db/schema.cds +105 -0
  11. package/package.json +9 -3
  12. package/src/index.d.ts +6 -0
  13. package/src/index.js +21 -1
  14. package/src/plugin.js +33 -30
  15. package/srv/blockchain/backends/blockfrost-backend.js +1 -10
  16. package/srv/blockchain/backends/koios-backend.js +1 -10
  17. package/srv/blockchain/backends/ogmios-backend.d.ts +23 -3
  18. package/srv/blockchain/backends/ogmios-backend.js +72 -5
  19. package/srv/blockchain/cardano-indexer.js +3 -1
  20. package/srv/blockchain/crawler/crawler.d.ts +25 -0
  21. package/srv/blockchain/crawler/crawler.js +68 -1
  22. package/srv/blockchain/crawler/index.d.ts +9 -0
  23. package/srv/blockchain/crawler/index.js +37 -4
  24. package/srv/blockchain/crawler/sync-state.d.ts +13 -1
  25. package/srv/blockchain/crawler/sync-state.js +24 -2
  26. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  27. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  28. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  29. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  30. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  31. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  32. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  33. package/srv/cardano-agent-service.cds +150 -0
  34. package/srv/cardano-agent-service.d.ts +2 -0
  35. package/srv/cardano-agent-service.js +16 -0
  36. package/srv/cardano-indexer-service.cds +36 -3
  37. package/srv/cardano-indexer-service.js +3 -0
  38. package/srv/cardano-service.js +57 -3
  39. package/srv/cardano-sign-service.cds +200 -180
  40. package/srv/cardano-tx-service.cds +32 -26
  41. package/srv/cardano-tx-service.js +96 -38
  42. package/srv/cardano-worker-service.cds +125 -125
  43. package/srv/server.d.ts +2 -1
  44. package/srv/server.js +18 -34
  45. package/srv/utils/agent-grants-config.d.ts +65 -0
  46. package/srv/utils/agent-grants-config.js +148 -0
  47. package/srv/utils/agent-grants.d.ts +314 -0
  48. package/srv/utils/agent-grants.js +821 -0
  49. package/srv/utils/agent-token-auth.d.ts +19 -0
  50. package/srv/utils/agent-token-auth.js +81 -0
  51. package/srv/utils/db-sanitize.d.ts +40 -0
  52. package/srv/utils/db-sanitize.js +98 -0
  53. package/srv/utils/liveness.d.ts +23 -0
  54. package/srv/utils/liveness.js +49 -0
  55. package/srv/utils/mappers.d.ts +27 -0
  56. package/srv/utils/mappers.js +67 -7
  57. package/srv/utils/rate-limiter.d.ts +57 -0
  58. package/srv/utils/rate-limiter.js +126 -0
  59. package/srv/utils/tx-request-parsers.d.ts +13 -0
  60. package/srv/utils/tx-request-parsers.js +32 -0
  61. package/srv/utils/types.d.ts +15 -0
@@ -42,6 +42,33 @@ class CardanoCrawler {
42
42
  leaseOwner;
43
43
  /** Transient-failure retries per block before giving up. */
44
44
  static PERSIST_RETRIES = 3;
45
+ /**
46
+ * A block whose persist keeps failing across crawler restarts is a poison block
47
+ * (e.g. data PostgreSQL rejects). After this many failed persistBlock() calls for
48
+ * the same hash the crawler latches off (desiredRunning=false) instead of
49
+ * restarting forever; an operator fixes the cause and calls resumeCrawler().
50
+ */
51
+ static POISON_BLOCK_THRESHOLD = 5;
52
+ /** Process-wide, survives instance restarts: the block currently failing and how often. */
53
+ static poison = null;
54
+ /**
55
+ * Database errors that are deterministic for the block's data — the same bytes fail
56
+ * the same way on every restart. Only these count towards the poison-block latch:
57
+ * a DB outage, a statement timeout or an exhausted pool fails the same block too,
58
+ * but a restart fixes those, and latching on them would disable the pre-sync for
59
+ * good (the contract of halt()).
60
+ */
61
+ static DATA_REJECTION_PATTERNS = [
62
+ /unsupported unicode escape sequence/i, // PostgreSQL: U+0000 inside a JSON document
63
+ /invalid byte sequence for encoding/i, // PostgreSQL: bytes that are not valid UTF-8
64
+ /out of range for type/i, // PostgreSQL: bigint / integer overflow
65
+ /invalid input syntax for type/i, // PostgreSQL: NaN or text in a numeric column
66
+ /value too long for type/i, // PostgreSQL: varchar(n) exceeded
67
+ /numeric value out of range/i, // HANA / SQL-92
68
+ /inserted value too large for column/i, // HANA
69
+ /string or blob too big/i, // SQLite
70
+ /datatype mismatch/i, // SQLite
71
+ ];
45
72
  /** Timeout for direct backend calls (the crawler bypasses the client's resilience layer). */
46
73
  static CALL_TIMEOUT_MS = 60_000;
47
74
  running = false;
@@ -73,6 +100,10 @@ class CardanoCrawler {
73
100
  isRunning() {
74
101
  return this.running;
75
102
  }
103
+ /** True once the crawler halted because of a failure (not via stop() or a lost lease). */
104
+ haltedWithError() {
105
+ return !this.running && this.finalStatus === 'error';
106
+ }
76
107
  /**
77
108
  * Start crawling. Does NOT await the ingest pipeline (fire-and-forget).
78
109
  * Refuses to start without a resume point: an explicit configured start block or an
@@ -506,6 +537,8 @@ class CardanoCrawler {
506
537
  await this.indexer.indexBlockFull(tx, block, txs);
507
538
  await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing');
508
539
  });
540
+ if (CardanoCrawler.poison?.hash === block.hash)
541
+ CardanoCrawler.poison = null;
509
542
  // Notify observers (wallet-worker confirmation tracker) AFTER the commit —
510
543
  // listener failures are swallowed inside emitBlockIndexed.
511
544
  (0, hooks_1.emitBlockIndexed)({
@@ -534,7 +567,23 @@ class CardanoCrawler {
534
567
  await this.sleep(1000 * attempt);
535
568
  continue;
536
569
  }
537
- logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts — stopping crawler (resume re-syncs from cursor):`, err);
570
+ const dataRejection = CardanoCrawler.isDataRejection(err);
571
+ const failures = dataRejection ? CardanoCrawler.notePersistFailure(block.hash) : 0;
572
+ if (failures >= CardanoCrawler.POISON_BLOCK_THRESHOLD) {
573
+ const cause = err instanceof Error ? err.message : String(err);
574
+ const message = `poison block ${block.hash} @${block.height ?? '?'} failed ${failures}x: ${cause}`;
575
+ logger.error(`persistBlock failed for ${block.hash} (height ${block.height}) ${failures}x across restarts — poison block, latching the crawler off. Fix the cause, then resumeCrawler():`, err);
576
+ // Lease-independent on purpose (see latchPoisonBlock). The memory is only
577
+ // forgotten once the latch is durable, so a failed write is retried after
578
+ // the next restart instead of restarting the count from one.
579
+ const latched = await cds_1.default.tx((tx) => (0, sync_state_1.latchPoisonBlock)(tx, message)).then(() => true, (e) => { logger.error('poison-block latch could not be written — retried after the next restart:', e); return false; });
580
+ if (latched)
581
+ CardanoCrawler.poison = null;
582
+ await this.halt('error', true);
583
+ return false;
584
+ }
585
+ const perBlock = dataRejection ? ` (${failures}/${CardanoCrawler.POISON_BLOCK_THRESHOLD} for this block)` : '';
586
+ logger.error(`persistBlock failed for ${block.hash} after ${attempt} attempts${perBlock} — stopping crawler (resume re-syncs from cursor):`, err);
538
587
  await this.halt('error');
539
588
  return false;
540
589
  }
@@ -650,6 +699,24 @@ class CardanoCrawler {
650
699
  }
651
700
  })();
652
701
  }
702
+ /** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
703
+ static isDataRejection(err) {
704
+ // RangeError: BigInt / number conversions in the mappers; SyntaxError: JSON of the block
705
+ if (err instanceof RangeError || err instanceof SyntaxError)
706
+ return true;
707
+ const message = err instanceof Error ? err.message : String(err);
708
+ return CardanoCrawler.DATA_REJECTION_PATTERNS.some((p) => p.test(message));
709
+ }
710
+ /** Count final persist failures per block hash (a different hash resets the count). */
711
+ static notePersistFailure(hash) {
712
+ const p = CardanoCrawler.poison;
713
+ CardanoCrawler.poison = p && p.hash === hash ? { hash, failures: p.failures + 1 } : { hash, failures: 1 };
714
+ return CardanoCrawler.poison.failures;
715
+ }
716
+ /** Test seam: forget the poison-block memory (process-wide state). */
717
+ static resetPoisonMemory() {
718
+ CardanoCrawler.poison = null;
719
+ }
653
720
  /** Record state only while this instance still owns the lease. */
654
721
  async recordCrawlerError(err) {
655
722
  if (err instanceof CrawlerStoppedError || err instanceof CrawlerLeaseLostError) {
@@ -1,6 +1,15 @@
1
1
  import type { CardanoClient } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { CardanoCrawler, type CrawlerConfig } from './crawler';
4
+ /**
5
+ * Delay before the next standby start attempt. A healthy standby (a lease loser, or
6
+ * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
7
+ * process halted with an error does the shared cursor's consecutiveErrors drive an
8
+ * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
9
+ * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
10
+ * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
11
+ */
12
+ export declare function standbyDelayMs(consecutiveErrors: number): number;
4
13
  export interface StartCrawlerDeps {
5
14
  client: CardanoClient;
6
15
  indexer: CardanoIndexer;
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.standbyDelayMs = standbyDelayMs;
6
7
  exports.startCrawler = startCrawler;
7
8
  exports.stopCrawler = stopCrawler;
8
9
  exports.isCrawlerRunning = isCrawlerRunning;
@@ -24,6 +25,20 @@ let standbyDeps = null;
24
25
  let standbyTimer = null;
25
26
  let standbyGeneration = 0;
26
27
  const STANDBY_RETRY_MS = 5_000;
28
+ const STANDBY_MAX_BACKOFF_MS = 5 * 60_000;
29
+ /**
30
+ * Delay before the next standby start attempt. A healthy standby (a lease loser, or
31
+ * the leader's own no-op tick) retries every 5 s. Only after the crawler in THIS
32
+ * process halted with an error does the shared cursor's consecutiveErrors drive an
33
+ * exponential backoff (5 s, 10 s, 20 s ... capped at 5 min), so a block the crawler
34
+ * cannot persist no longer re-syncs the chain-sync stream every 5 s. A standby that
35
+ * never held the lease is not slowed down by the leader's streak: failover stays 5 s.
36
+ */
37
+ function standbyDelayMs(consecutiveErrors) {
38
+ if (!Number.isFinite(consecutiveErrors) || consecutiveErrors <= 1)
39
+ return STANDBY_RETRY_MS;
40
+ return Math.min(STANDBY_MAX_BACKOFF_MS, STANDBY_RETRY_MS * 2 ** Math.min(consecutiveErrors - 1, 10));
41
+ }
27
42
  /**
28
43
  * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
29
44
  * returns once the ingest pipeline is launched, not when catch-up completes.
@@ -113,7 +128,7 @@ function serializeLifecycle(operation) {
113
128
  return result;
114
129
  }
115
130
  /** Keep non-leader instances warm so an expired/released lease fails over automatically. */
116
- function scheduleStandby(generation) {
131
+ function scheduleStandby(generation, delayMs = STANDBY_RETRY_MS) {
117
132
  if (standbyTimer || !standbyDeps)
118
133
  return;
119
134
  standbyTimer = setTimeout(() => {
@@ -123,13 +138,31 @@ function scheduleStandby(generation) {
123
138
  const deps = standbyDeps;
124
139
  if (!deps)
125
140
  return;
141
+ // Local evidence only, taken BEFORE the attempt replaces `active`.
142
+ const failedHere = active?.haltedWithError() ?? false;
126
143
  void startCrawlerAttempt(deps, false, generation)
127
144
  .catch((err) => logger.error('standby lease attempt failed:', err))
128
- .finally(() => {
145
+ .then(() => nextStandbyDelay(failedHere))
146
+ .then((delay) => {
129
147
  if (generation === standbyGeneration)
130
- scheduleStandby(generation);
148
+ scheduleStandby(generation, delay);
131
149
  });
132
- }, STANDBY_RETRY_MS);
150
+ }, delayMs);
133
151
  standbyTimer.unref?.();
134
152
  }
153
+ /**
154
+ * Backoff from the shared cursor's error streak after a local failure; the base delay
155
+ * otherwise — a healthy tick costs no DB round-trip.
156
+ */
157
+ async function nextStandbyDelay(failedHere) {
158
+ if (!failedHere)
159
+ return STANDBY_RETRY_MS;
160
+ try {
161
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
162
+ return standbyDelayMs(cursor?.consecutiveErrors ?? 0);
163
+ }
164
+ catch {
165
+ return STANDBY_RETRY_MS;
166
+ }
167
+ }
135
168
  //# sourceMappingURL=index.js.map
@@ -70,8 +70,20 @@ export declare function renewCrawlerLease(db: CapTransaction, owner: string, now
70
70
  * exactly the cases where coming back up should resume the pre-sync by itself.
71
71
  */
72
72
  export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
73
- /** Persist the pause/resume intent shared by every app instance. */
73
+ /**
74
+ * Persist the pause/resume intent shared by every app instance. Resuming also clears
75
+ * the error streak: the operator says the cause is fixed, and a stale streak would
76
+ * otherwise keep the standby backoff at its cap for the first retry.
77
+ */
74
78
  export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
79
+ /**
80
+ * Latch the cluster off because of a poison block (a block whose data the database
81
+ * deterministically rejects). Deliberately NOT lease-scoped, unlike releaseCrawlerLease:
82
+ * the poison is a property of the block, not of the instance that observed it, and
83
+ * that instance may have lost its lease while the failure was being recorded. Only
84
+ * an operator's resumeCrawler brings the crawler back.
85
+ */
86
+ export declare function latchPoisonBlock(db: CapTransaction, message: string): Promise<void>;
75
87
  /**
76
88
  * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
77
89
  * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
@@ -11,6 +11,7 @@ exports.tryAcquireCrawlerLease = tryAcquireCrawlerLease;
11
11
  exports.renewCrawlerLease = renewCrawlerLease;
12
12
  exports.releaseCrawlerLease = releaseCrawlerLease;
13
13
  exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
+ exports.latchPoisonBlock = latchPoisonBlock;
14
15
  exports.advanceCursor = advanceCursor;
15
16
  exports.resetCursorTo = resetCursorTo;
16
17
  exports.setSyncStatus = setSyncStatus;
@@ -197,13 +198,34 @@ async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
197
198
  ...(pauseCluster ? { desiredRunning: false } : {}),
198
199
  }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
199
200
  }
200
- /** Persist the pause/resume intent shared by every app instance. */
201
+ /**
202
+ * Persist the pause/resume intent shared by every app instance. Resuming also clears
203
+ * the error streak: the operator says the cause is fixed, and a stale streak would
204
+ * otherwise keep the standby backoff at its cap for the first retry.
205
+ */
201
206
  async function setCrawlerDesiredRunning(db, desiredRunning) {
202
207
  const set = { desiredRunning };
203
- if (!desiredRunning)
208
+ if (desiredRunning)
209
+ set.consecutiveErrors = 0;
210
+ else
204
211
  set.syncStatus = 'stopped';
205
212
  await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
206
213
  }
214
+ /**
215
+ * Latch the cluster off because of a poison block (a block whose data the database
216
+ * deterministically rejects). Deliberately NOT lease-scoped, unlike releaseCrawlerLease:
217
+ * the poison is a property of the block, not of the instance that observed it, and
218
+ * that instance may have lost its lease while the failure was being recorded. Only
219
+ * an operator's resumeCrawler brings the crawler back.
220
+ */
221
+ async function latchPoisonBlock(db, message) {
222
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
223
+ desiredRunning: false,
224
+ syncStatus: 'error',
225
+ lastError: message.slice(0, 500),
226
+ lastErrorAt: new Date().toISOString(),
227
+ }).where({ ID: exports.SINGLETON_ID }));
228
+ }
207
229
  /**
208
230
  * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
209
231
  * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
@@ -140,10 +140,30 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
140
140
  * Returns empty array when no reference inputs are provided.
141
141
  */
142
142
  private _mapReferenceInputs;
143
+ /**
144
+ * Funding requirement contributed by extra outputs on a mint build:
145
+ * the summed lovelace of all entries plus, per asset unit, the demand the
146
+ * transaction's own positive mints do NOT cover. Minted quantities are
147
+ * aggregated per unit and subtracted from the aggregated output demand;
148
+ * only a positive remainder is requested from the wallet (a fully covered
149
+ * unit is not requested at all — it does not exist before this tx).
150
+ */
151
+ private _extraOutputsFundingAfterMint;
152
+ /**
153
+ * The script an individual mint action executes under: its own
154
+ * per-action policy when set (multi-policy mint FR), else the request's
155
+ * top-level policy script.
156
+ */
157
+ private _mintActionScript;
143
158
  /**
144
159
  * Build the Buildooor mint-entry array shared by the mint-only flow and the
145
160
  * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
146
161
  * they are stamped into the redeemers post-build by _buildScriptTx).
162
+ *
163
+ * Multi-policy mint FR: each action may carry its own policy script and
164
+ * redeemer; absent fields fall back to the request-level ones. The ledger
165
+ * carries ONE redeemer per policy, so actions resolving to the same policy
166
+ * must agree on their redeemer, checked here.
147
167
  */
148
168
  private _buildMintEntries;
149
169
  /**
@@ -246,13 +246,15 @@ class BuildooorTxBuilder {
246
246
  const changeAddress = cardano_ledger_ts_1.Address.fromString(req.changeAddress ?? req.senderAddress);
247
247
  // Parse the minting policy script once
248
248
  const script = this._parsePlutusV3Script(req.mintingPolicyScript, 'mintingPolicyScript');
249
- // Calculate total mint value for output (only positive quantities - mints, not burns)
249
+ // Calculate total mint value for output (only positive quantities - mints, not burns).
250
+ // Multi-policy mint FR: each action mints under ITS script (own or top-level).
250
251
  let mintValue = cardano_ledger_ts_1.Value.lovelaces(0n);
251
- for (const mintAction of req.mintActions) {
252
+ for (const [index, mintAction] of req.mintActions.entries()) {
252
253
  const quantity = BigInt(mintAction.quantity);
253
254
  if (quantity > 0n) {
255
+ const actionScript = this._mintActionScript(mintAction, script, index);
254
256
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(mintAction.assetUnit);
255
- mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), quantity));
257
+ mintValue = cardano_ledger_ts_1.Value.add(mintValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), quantity));
256
258
  }
257
259
  }
258
260
  // Partition forced vs candidate UTxOs. Forced inputs are already committed;
@@ -264,8 +266,15 @@ class BuildooorTxBuilder {
264
266
  coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
265
267
  const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
266
268
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
267
- // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
268
- const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
269
+ // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from
270
+ // thin air). Extra outputs (FR-2 on mint) add their lovelace plus, per unit, the
271
+ // demand the mint does NOT cover (e.g. minting 1 while placing 2 means 1 must come
272
+ // from the wallet).
273
+ let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
274
+ if (req.extraOutputs && req.extraOutputs.length > 0) {
275
+ const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
276
+ requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
277
+ }
269
278
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
270
279
  const inputs = [...forcedInputs, ...selectedFunding];
271
280
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
@@ -281,15 +290,24 @@ class BuildooorTxBuilder {
281
290
  const resolvedInlineDatum = req.inlineDatum
282
291
  ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(req.inlineDatum, resolveCtx)
283
292
  : undefined;
284
- // Build output — recipient gets the minted assets + min ADA
293
+ const resolvedExtraOutputs = this._resolveExtraOutputPlaceholders(req.extraOutputs, resolveCtx);
294
+ // Build output — recipient gets the minted assets + min ADA. When extra
295
+ // outputs are declared (FR-2 on mint) THEY carry the minted assets (each
296
+ // token on its own output with its own datum, e.g. datum-bound predicate
297
+ // tokens), so the primary output stays ADA(+datum)-only.
285
298
  let outputValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
286
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
299
+ if (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0) {
300
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, mintValue);
301
+ }
287
302
  const refScript = this._parseReferenceScript(req.referenceScript);
288
303
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
289
- // Mint entries for the build args (uses pre-resolved redeemer). Note: Buildooor
290
- // ignores caller-supplied execution units — the real units are stamped into the
304
+ // Append extra outputs, each independently min-ADA checked.
305
+ this._appendExtraOutputs(outputs, resolvedExtraOutputs);
306
+ // Mint entries for the build args (uses pre-resolved redeemers; per-action
307
+ // redeemers resolve their own placeholders). Note: Buildooor ignores
308
+ // caller-supplied execution units — the real units are stamped into the
291
309
  // redeemers post-build by _buildScriptTx.
292
- const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer);
310
+ const mints = this._buildMintEntries(req.mintActions, script, resolvedMintRedeemer, resolveCtx);
293
311
  // CIP-31: map resolved reference input UTxOs to Buildooor LedgerUTxO format
294
312
  const readonlyRefInputs = this._mapReferenceInputs(ctx.referenceInputUtxos);
295
313
  // Resolve validity bounds once — both passes must share them so redeemer ExUnits
@@ -394,11 +412,12 @@ class BuildooorTxBuilder {
394
412
  }
395
413
  // If mints are present and no extraOutputs handle the minted assets, attach positive mints to the primary output.
396
414
  if (hasMint && (!resolvedExtraOutputs || resolvedExtraOutputs.length === 0)) {
397
- for (const action of req.mintActions) {
415
+ for (const [index, action] of req.mintActions.entries()) {
398
416
  const qty = BigInt(action.quantity);
399
417
  if (qty > 0n) {
418
+ const actionScript = this._mintActionScript(action, mintScript, index);
400
419
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
401
- outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), qty));
420
+ outputValue = cardano_ledger_ts_1.Value.add(outputValue, cardano_ledger_ts_1.Value.singleAsset(actionScript.hash, Buffer.from(assetName, 'hex'), qty));
402
421
  }
403
422
  }
404
423
  }
@@ -411,7 +430,7 @@ class BuildooorTxBuilder {
411
430
  // caller-supplied execution units — the real units are stamped into the
412
431
  // redeemers post-build by _buildScriptTx.
413
432
  const mints = hasMint
414
- ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer)
433
+ ? this._buildMintEntries(req.mintActions, mintScript, resolvedMintRedeemer, resolveCtx)
415
434
  : undefined;
416
435
  const scriptInput = {
417
436
  utxo: scriptLedgerUtxo,
@@ -760,21 +779,86 @@ class BuildooorTxBuilder {
760
779
  return [];
761
780
  return referenceInputUtxos.map(u => this._mapMultiAssetUtxoToLedgerUtxo(u));
762
781
  }
782
+ /**
783
+ * Funding requirement contributed by extra outputs on a mint build:
784
+ * the summed lovelace of all entries plus, per asset unit, the demand the
785
+ * transaction's own positive mints do NOT cover. Minted quantities are
786
+ * aggregated per unit and subtracted from the aggregated output demand;
787
+ * only a positive remainder is requested from the wallet (a fully covered
788
+ * unit is not requested at all — it does not exist before this tx).
789
+ */
790
+ _extraOutputsFundingAfterMint(mintActions, extraOutputs) {
791
+ const mintedByUnit = new Map();
792
+ for (const action of mintActions) {
793
+ const quantity = BigInt(action.quantity);
794
+ if (quantity > 0n) {
795
+ const unit = action.assetUnit.toLowerCase();
796
+ mintedByUnit.set(unit, (mintedByUnit.get(unit) ?? 0n) + quantity);
797
+ }
798
+ }
799
+ const demandByUnit = new Map();
800
+ let lovelace = 0n;
801
+ for (const extra of extraOutputs) {
802
+ lovelace += BigInt(extra.lovelaceAmount);
803
+ for (const asset of extra.assets ?? []) {
804
+ const unit = asset.unit.toLowerCase();
805
+ demandByUnit.set(unit, (demandByUnit.get(unit) ?? 0n) + BigInt(asset.quantity));
806
+ }
807
+ }
808
+ const assets = [];
809
+ for (const [unit, demand] of demandByUnit) {
810
+ const uncovered = demand - (mintedByUnit.get(unit) ?? 0n);
811
+ if (uncovered > 0n)
812
+ assets.push({ unit, quantity: uncovered.toString() });
813
+ }
814
+ return { lovelace, ...(assets.length > 0 ? { assets } : {}) };
815
+ }
816
+ /**
817
+ * The script an individual mint action executes under: its own
818
+ * per-action policy when set (multi-policy mint FR), else the request's
819
+ * top-level policy script.
820
+ */
821
+ _mintActionScript(action, defaultScript, index) {
822
+ if (!action.mintingPolicyScript)
823
+ return defaultScript;
824
+ return this._parsePlutusV3Script(action.mintingPolicyScript, `mintActions[${index}].mintingPolicyScript`);
825
+ }
763
826
  /**
764
827
  * Build the Buildooor mint-entry array shared by the mint-only flow and the
765
828
  * combined spend+mint flow (Buildooor ignores caller-supplied execution units;
766
829
  * they are stamped into the redeemers post-build by _buildScriptTx).
830
+ *
831
+ * Multi-policy mint FR: each action may carry its own policy script and
832
+ * redeemer; absent fields fall back to the request-level ones. The ledger
833
+ * carries ONE redeemer per policy, so actions resolving to the same policy
834
+ * must agree on their redeemer, checked here.
767
835
  */
768
- _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer) {
769
- return mintActions.map(action => {
836
+ _buildMintEntries(mintActions, mintScript, resolvedMintRedeemer, resolveCtx) {
837
+ const redeemerByPolicy = new Map();
838
+ return mintActions.map((action, index) => {
839
+ const script = this._mintActionScript(action, mintScript, index);
840
+ const actionRedeemer = action.redeemerJson !== undefined
841
+ ? (resolveCtx ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(action.redeemerJson, resolveCtx) : action.redeemerJson)
842
+ : resolvedMintRedeemer;
843
+ const redeemerData = actionRedeemer !== undefined
844
+ ? (0, tx_build_helper_1.jsonToPlutusData)(actionRedeemer)
845
+ : new plutus_data_1.DataI(action.redeemer ?? 0);
846
+ const policyId = script.hash.toString();
847
+ // Canonical comparison over the encoded PlutusData: JSON key order must
848
+ // not matter, and a JSON {int:0} equals the DataI(0) fallback.
849
+ const redeemerFingerprint = (0, plutus_data_1.dataToCbor)(redeemerData).toString();
850
+ const seen = redeemerByPolicy.get(policyId);
851
+ if (seen !== undefined && seen !== redeemerFingerprint) {
852
+ throw new Error(`mint actions under policy ${policyId} carry different redeemers — the ledger allows one redeemer per policy; ` +
853
+ 'split them into separate transactions or align the redeemers');
854
+ }
855
+ redeemerByPolicy.set(policyId, redeemerFingerprint);
770
856
  const { assetName } = (0, tx_build_helper_1.parseAssetUnit)(action.assetUnit);
771
857
  return {
772
- value: cardano_ledger_ts_1.Value.singleAsset(mintScript.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
858
+ value: cardano_ledger_ts_1.Value.singleAsset(script.hash, Buffer.from(assetName, 'hex'), BigInt(action.quantity)),
773
859
  script: {
774
- inline: mintScript,
775
- redeemer: resolvedMintRedeemer
776
- ? (0, tx_build_helper_1.jsonToPlutusData)(resolvedMintRedeemer)
777
- : new plutus_data_1.DataI(action.redeemer ?? 0)
860
+ inline: script,
861
+ redeemer: redeemerData
778
862
  }
779
863
  };
780
864
  });
@@ -42,12 +42,13 @@ function parseScriptParams(raw) {
42
42
  fail('scriptParamsJson must be a JSON array');
43
43
  return parsed;
44
44
  }
45
- /** Mirrors the BuildMint/BuildPlutusSpend mint-action parsing (bigint quantities). */
45
+ /** Mirrors the BuildMint/BuildPlutusSpend mint-action parsing (bigint quantities,
46
+ * multi-policy per-action fields). */
46
47
  function parseMintActions(raw, allowBareNames) {
47
48
  const parsed = parseJsonField(raw, 'mintActionsJson');
48
49
  if (!Array.isArray(parsed))
49
50
  fail('mintActionsJson must be a JSON array');
50
- return parsed.map((rawAction) => {
51
+ return parsed.map((rawAction, i) => {
51
52
  if (!rawAction || typeof rawAction !== 'object') {
52
53
  fail('Each mint action must be an object with assetUnit and quantity');
53
54
  }
@@ -57,14 +58,37 @@ function parseMintActions(raw, allowBareNames) {
57
58
  }
58
59
  if (typeof action.assetUnit !== 'string')
59
60
  fail('Each mint action must have an assetUnit string');
60
- const bareAssetNameForExpansion = allowBareNames &&
61
+ // Multi-policy mint FR: optional per-action mintingPolicyScript + redeemerJson.
62
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, i);
63
+ if (policyFields.error)
64
+ fail(policyFields.error);
65
+ let actionPolicyId;
66
+ if (policyFields.script) {
67
+ actionPolicyId = scriptHashOf(policyFields.script, `mintActions[${i}].mintingPolicyScript is not a valid Plutus script`);
68
+ }
69
+ const bareAssetNameForExpansion = (allowBareNames || !!actionPolicyId) &&
61
70
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
62
71
  action.assetUnit.length % 2 === 0 &&
63
72
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
64
73
  if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
65
- fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson is set)`);
74
+ fail(`Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson or a per-action mintingPolicyScript is set)`);
75
+ }
76
+ let assetUnit = action.assetUnit;
77
+ if (actionPolicyId) {
78
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
79
+ assetUnit = actionPolicyId + assetUnit;
80
+ }
81
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
82
+ fail(`mintActions[${i}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`);
83
+ }
66
84
  }
67
- return { assetUnit: action.assetUnit, quantity: BigInt(action.quantity) };
85
+ return {
86
+ assetUnit,
87
+ quantity: BigInt(action.quantity),
88
+ ...(typeof action.redeemer === 'number' ? { redeemer: action.redeemer } : {}),
89
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
90
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
91
+ };
68
92
  });
69
93
  }
70
94
  function scriptHashOf(scriptHex, context) {
@@ -81,7 +105,9 @@ function scriptHashOf(scriptHex, context) {
81
105
  * would mint a truncated asset name.
82
106
  */
83
107
  function assertPolicyPrefix(actions, policyId) {
84
- const mismatch = actions.find((a) => !a.assetUnit.toLowerCase().startsWith(policyId));
108
+ // Actions with their own per-action script were already checked against THAT
109
+ // script's policy id during parsing.
110
+ const mismatch = actions.find((a) => !a.mintingPolicyScript && !a.assetUnit.toLowerCase().startsWith(policyId));
85
111
  if (mismatch) {
86
112
  fail(`assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`);
87
113
  }
@@ -153,6 +179,7 @@ function prepareMint(raw, network) {
153
179
  const mintRedeemer = parseJsonField(raw, 'mintRedeemerJson');
154
180
  const forceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.forceInputsJson, 'forceInputsJson'));
155
181
  const referenceInputs = takeParsed((0, tx_request_parsers_1.parseUtxoRefArray)(raw.referenceInputsJson, 'referenceInputsJson'));
182
+ const extraOutputs = takeParsed((0, tx_request_parsers_1.parseExtraOutputs)(raw.extraOutputsJson));
156
183
  if (raw.lockOnScript && (!scriptParams || scriptParams.length === 0)) {
157
184
  fail('lockOnScript requires scriptParamsJson to derive script address');
158
185
  }
@@ -172,6 +199,7 @@ function prepareMint(raw, network) {
172
199
  delete clean.lockOnScript;
173
200
  delete clean.forceInputsJson;
174
201
  delete clean.referenceInputsJson;
202
+ delete clean.extraOutputsJson;
175
203
  if (parsedMetadata)
176
204
  clean.metadataJson = parsedMetadata;
177
205
  else
@@ -219,6 +247,7 @@ function prepareMint(raw, network) {
219
247
  mintRedeemer,
220
248
  forceInputs,
221
249
  referenceInputs,
250
+ extraOutputs,
222
251
  };
223
252
  }
224
253
  function preparePlutusSpend(raw, network) {
@@ -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