@odatano/core 2.0.0-rc.28 → 2.0.0-rc.29

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.
@@ -92,7 +92,8 @@ export declare function getErrorStatus(err: HttpErrorLike | unknown): number;
92
92
  /** Message of an HttpErrorLike: `response.data.error` (Koios), else `message`. */
93
93
  export declare function getErrorMessage(err: HttpErrorLike | unknown): string;
94
94
  /**
95
- * Normalizes any backend error into a typed BackendError. Message hints are checked in priority
95
+ * Normalizes any backend error into a typed BackendError. An Ogmios script failure is recognised
96
+ * by its JSON-RPC code. Message hints are then checked in priority
96
97
  * order (already submitted, script failure, validation, not found, rate limit) before the HTTP status.
97
98
  */
98
99
  export declare function normalizeBackendError(err: unknown, backendName?: string): BackendError;
@@ -168,8 +168,13 @@ function getErrorMessage(err) {
168
168
  return e.message;
169
169
  return 'Unknown error';
170
170
  }
171
+ /** Ogmios JSON-RPC code of a failed script evaluation. */
172
+ const OGMIOS_SCRIPT_EXECUTION_FAILURE = 3010;
173
+ /** Characters of Ogmios error data kept in a message. */
174
+ const OGMIOS_DETAIL_MAX = 2000;
171
175
  /**
172
- * Normalizes any backend error into a typed BackendError. Message hints are checked in priority
176
+ * Normalizes any backend error into a typed BackendError. An Ogmios script failure is recognised
177
+ * by its JSON-RPC code. Message hints are then checked in priority
173
178
  * order (already submitted, script failure, validation, not found, rate limit) before the HTTP status.
174
179
  */
175
180
  function normalizeBackendError(err, backendName) {
@@ -183,6 +188,12 @@ function normalizeBackendError(err, backendName) {
183
188
  err.message.includes('undefined is not an object'))) {
184
189
  return new BackendInitError(backendName || 'unknown', new Error('Backend client not initialized - call init() first'));
185
190
  }
191
+ // Ogmios evaluateTransaction 3010: a script failed. Its data names each failing validator.
192
+ const rpc = err;
193
+ if (rpc?.code === OGMIOS_SCRIPT_EXECUTION_FAILURE) {
194
+ const detail = rpc.data === undefined ? '' : ` ${JSON.stringify(rpc.data).slice(0, OGMIOS_DETAIL_MAX)}`;
195
+ return new ScriptValidationError(`Script validation failed (${rpc.code}): ${String(rpc.message ?? '')}${detail}`, err);
196
+ }
186
197
  const message = getErrorMessage(err);
187
198
  const status = getErrorStatus(err);
188
199
  const messageLower = message.toLowerCase();
@@ -4,20 +4,39 @@ import type { JSONValue } from './types';
4
4
  * entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
5
5
  */
6
6
  export declare const INPUT_IDX_REGEX: RegExp;
7
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
8
+ export declare const REF_IDX_REGEX: RegExp;
9
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
10
+ export declare const WDRL_IDX_REGEX: RegExp;
7
11
  /** Minimal UTxO reference shape used by the placeholder resolver. */
8
12
  export interface InputRef {
9
13
  txHash: string;
10
14
  outputIndex: number;
11
15
  }
16
+ /** Credential of a reward account, as the ledger orders withdrawals. */
17
+ export interface WithdrawalCredential {
18
+ credentialHash: string;
19
+ isScript: boolean;
20
+ }
12
21
  export interface ResolveContext {
13
22
  /** Inputs in their final, post-sort order; the array index is the resolved placeholder value. */
14
23
  sortedInputs: InputRef[];
24
+ /** All reference inputs in ledger order; absent where the build does not support `__REF_IDX__`. */
25
+ sortedReferenceInputs?: InputRef[];
26
+ /** Withdrawal credential hashes in ledger order; absent where the build does not support `__WDRL_IDX__`. */
27
+ sortedWithdrawals?: string[];
15
28
  }
16
- /** Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc. */
29
+ /**
30
+ * Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc.
31
+ * The ledger orders reference inputs the same way.
32
+ */
17
33
  export declare function sortInputsLikeBuildooor<T extends InputRef>(refs: T[]): T[];
34
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
35
+ export declare function sortWithdrawalsLikeLedger<T extends WithdrawalCredential>(entries: T[]): T[];
18
36
  /**
19
- * Replaces `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves with the input's sorted position. Only `int`
20
- * fields are inspected (`bytes` may legitimately contain `__`); an unknown ref throws TransactionValidationError.
37
+ * Replaces `{int: "__INPUT_IDX:…__"}`, `{int: "__REF_IDX:…__"}` and `{int: "__WDRL_IDX:…__"}` leaves with
38
+ * the position in the matching list. Only `int` fields are inspected (`bytes` may legitimately contain
39
+ * `__`); an unknown ref throws TransactionValidationError.
21
40
  */
22
41
  export declare function resolveIndexPlaceholders(node: JSONValue, ctx: ResolveContext): JSONValue;
23
42
  //# sourceMappingURL=plutus-placeholders.d.ts.map
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.INPUT_IDX_REGEX = void 0;
3
+ exports.WDRL_IDX_REGEX = exports.REF_IDX_REGEX = exports.INPUT_IDX_REGEX = void 0;
4
4
  exports.sortInputsLikeBuildooor = sortInputsLikeBuildooor;
5
+ exports.sortWithdrawalsLikeLedger = sortWithdrawalsLikeLedger;
5
6
  exports.resolveIndexPlaceholders = resolveIndexPlaceholders;
6
7
  const errors_1 = require("./errors");
7
8
  /**
@@ -9,8 +10,15 @@ const errors_1 = require("./errors");
9
10
  * entire `int` field value. Hash case-insensitive, normalized to lowercase at the use site.
10
11
  */
11
12
  exports.INPUT_IDX_REGEX = /^__INPUT_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
13
+ /** Reference-input index placeholder `__REF_IDX:<64-hex txHash>#<outputIndex>__`, same rules as INPUT_IDX_REGEX. */
14
+ exports.REF_IDX_REGEX = /^__REF_IDX:([0-9a-fA-F]{64})#(\d+)__$/;
15
+ /** Withdrawal index placeholder `__WDRL_IDX:<56-hex credential hash>__`, same rules as INPUT_IDX_REGEX. */
16
+ exports.WDRL_IDX_REGEX = /^__WDRL_IDX:([0-9a-fA-F]{56})__$/;
12
17
  const MAX_WALK_DEPTH = 64;
13
- /** Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc. */
18
+ /**
19
+ * Replicates Buildooor's input sort (ledger CBOR-set order): txHash bytes, then outputIndex asc.
20
+ * The ledger orders reference inputs the same way.
21
+ */
14
22
  function sortInputsLikeBuildooor(refs) {
15
23
  const copy = refs.slice();
16
24
  copy.sort((a, b) => {
@@ -23,13 +31,62 @@ function sortInputsLikeBuildooor(refs) {
23
31
  });
24
32
  return copy;
25
33
  }
34
+ /** Ledger order of withdrawals: script credentials before key credentials, then hash bytes. */
35
+ function sortWithdrawalsLikeLedger(entries) {
36
+ const copy = entries.slice();
37
+ copy.sort((a, b) => {
38
+ if (a.isScript !== b.isScript)
39
+ return a.isScript ? -1 : 1;
40
+ return Buffer.compare(Buffer.from(a.credentialHash, 'hex'), Buffer.from(b.credentialHash, 'hex'));
41
+ });
42
+ return copy;
43
+ }
26
44
  /**
27
- * Replaces `{int: "__INPUT_IDX:<hash>#<idx>__"}` leaves with the input's sorted position. Only `int`
28
- * fields are inspected (`bytes` may legitimately contain `__`); an unknown ref throws TransactionValidationError.
45
+ * Replaces `{int: "__INPUT_IDX:…__"}`, `{int: "__REF_IDX:…__"}` and `{int: "__WDRL_IDX:…__"}` leaves with
46
+ * the position in the matching list. Only `int` fields are inspected (`bytes` may legitimately contain
47
+ * `__`); an unknown ref throws TransactionValidationError.
29
48
  */
30
49
  function resolveIndexPlaceholders(node, ctx) {
31
50
  return walk(node, ctx, 0);
32
51
  }
52
+ function positionOf(value, ctx) {
53
+ const input = exports.INPUT_IDX_REGEX.exec(value);
54
+ if (input) {
55
+ const txHash = input[1].toLowerCase(); // input refs are validated lowercase
56
+ const outputIndex = Number(input[2]);
57
+ const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
58
+ if (pos === -1) {
59
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
60
+ }
61
+ return pos;
62
+ }
63
+ const ref = exports.REF_IDX_REGEX.exec(value);
64
+ if (ref) {
65
+ if (!ctx.sortedReferenceInputs) {
66
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
67
+ }
68
+ const txHash = ref[1].toLowerCase();
69
+ const outputIndex = Number(ref[2]);
70
+ const pos = ctx.sortedReferenceInputs.findIndex(r => r.txHash === txHash && r.outputIndex === outputIndex);
71
+ if (pos === -1) {
72
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references ${txHash}#${outputIndex}, which is not a reference input of the transaction`);
73
+ }
74
+ return pos;
75
+ }
76
+ const wdrl = exports.WDRL_IDX_REGEX.exec(value);
77
+ if (wdrl) {
78
+ if (!ctx.sortedWithdrawals) {
79
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" is supported by BuildPlutusTransaction only`);
80
+ }
81
+ const credentialHash = wdrl[1].toLowerCase();
82
+ const pos = ctx.sortedWithdrawals.indexOf(credentialHash);
83
+ if (pos === -1) {
84
+ throw new errors_1.TransactionValidationError(`Placeholder "${value}" references credential ${credentialHash}, which has no withdrawal in the transaction`);
85
+ }
86
+ return pos;
87
+ }
88
+ return undefined;
89
+ }
33
90
  function walk(node, ctx, depth) {
34
91
  if (depth > MAX_WALK_DEPTH) {
35
92
  throw new errors_1.TransactionValidationError(`PlutusData placeholder walker exceeded max depth ${MAX_WALK_DEPTH}`);
@@ -42,15 +99,8 @@ function walk(node, ctx, depth) {
42
99
  const out = {};
43
100
  for (const [key, value] of Object.entries(node)) {
44
101
  if (key === 'int' && typeof value === 'string') {
45
- const match = exports.INPUT_IDX_REGEX.exec(value);
46
- if (match) {
47
- const [, rawTxHash, idxStr] = match;
48
- const txHash = rawTxHash.toLowerCase(); // input refs are validated lowercase
49
- const outputIndex = Number(idxStr);
50
- const pos = ctx.sortedInputs.findIndex(ref => ref.txHash === txHash && ref.outputIndex === outputIndex);
51
- if (pos === -1) {
52
- throw new errors_1.TransactionValidationError(`Placeholder "${value}" references input ${txHash}#${outputIndex} that is not in the final transaction input set`);
53
- }
102
+ const pos = positionOf(value, ctx);
103
+ if (pos !== undefined) {
54
104
  out[key] = pos;
55
105
  continue;
56
106
  }
@@ -52,7 +52,7 @@ export declare function parseOutputList(json: string | undefined, fieldName: 'ex
52
52
  * Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
53
53
  * applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
54
54
  */
55
- export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number): {
55
+ export declare function parseMintActionPolicyFields(entry: Record<string, unknown>, i: number, byReference?: boolean): {
56
56
  script?: string;
57
57
  redeemer?: JSONValue;
58
58
  error?: string;
@@ -124,8 +124,8 @@ export declare function parseCertificates(json: string | undefined): {
124
124
  };
125
125
  /**
126
126
  * Parse mintActionsJson for BuildPlutusTransaction: every action carries its own `mintingPolicyScript`
127
- * (no request-level default) and optional `redeemerJson`; `assetUnit` is policyId+assetName, or a bare
128
- * assetName that is prefixed with the policy id of the action's script.
127
+ * or `referenceScript` (no request-level default) and optional `redeemerJson`; `assetUnit` is
128
+ * policyId+assetName, or with an inline script a bare assetName prefixed with the script's policy id.
129
129
  */
130
130
  export declare function parsePolicyMintActions(json: string | undefined): {
131
131
  parsed?: MintAction[];
@@ -209,7 +209,7 @@ function parseOutputList(json, fieldName) {
209
209
  * Parse the optional per-action policy fields of a mintActionsJson entry: `mintingPolicyScript` (CBOR hex,
210
210
  * applied as-is) and `redeemerJson` (JSON string). Absent fields fall back to the top-level script/redeemer.
211
211
  */
212
- function parseMintActionPolicyFields(entry, i) {
212
+ function parseMintActionPolicyFields(entry, i, byReference = false) {
213
213
  let script;
214
214
  if (entry.mintingPolicyScript !== undefined && entry.mintingPolicyScript !== null) {
215
215
  if (typeof entry.mintingPolicyScript !== 'string' || !(0, validators_1.isValidCbor)(entry.mintingPolicyScript)) {
@@ -227,7 +227,7 @@ function parseMintActionPolicyFields(entry, i) {
227
227
  return { error: jsonResult.error };
228
228
  redeemer = jsonResult.parsed;
229
229
  }
230
- if (redeemer !== undefined && script === undefined) {
230
+ if (redeemer !== undefined && script === undefined && !byReference) {
231
231
  return { error: `mintActions[${i}].redeemerJson requires mintActions[${i}].mintingPolicyScript` };
232
232
  }
233
233
  return { script, redeemer };
@@ -493,8 +493,8 @@ function parseCertificates(json) {
493
493
  }
494
494
  /**
495
495
  * Parse mintActionsJson for BuildPlutusTransaction: every action carries its own `mintingPolicyScript`
496
- * (no request-level default) and optional `redeemerJson`; `assetUnit` is policyId+assetName, or a bare
497
- * assetName that is prefixed with the policy id of the action's script.
496
+ * or `referenceScript` (no request-level default) and optional `redeemerJson`; `assetUnit` is
497
+ * policyId+assetName, or with an inline script a bare assetName prefixed with the script's policy id.
498
498
  */
499
499
  function parsePolicyMintActions(json) {
500
500
  if (!json)
@@ -514,35 +514,52 @@ function parsePolicyMintActions(json) {
514
514
  if (typeof entry.quantity !== 'string' || !/^-?\d+$/.test(entry.quantity) || BigInt(entry.quantity) === 0n) {
515
515
  return { error: `mintActions[${i}].quantity must be a non-zero integer string` };
516
516
  }
517
- if (entry.mintingPolicyScript === undefined || entry.mintingPolicyScript === null) {
518
- return { error: `mintActions[${i}].mintingPolicyScript is required` };
517
+ const present = (v) => v !== undefined && v !== null;
518
+ const hasRef = present(entry.referenceScript);
519
+ if (present(entry.mintingPolicyScript) === hasRef) {
520
+ return { error: `mintActions[${i}] needs exactly one of mintingPolicyScript or referenceScript` };
519
521
  }
520
- const policy = parseMintActionPolicyFields(entry, i);
522
+ const policy = parseMintActionPolicyFields(entry, i, hasRef);
521
523
  if (policy.error)
522
524
  return { error: policy.error };
523
- let policyId;
524
- try {
525
- policyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policy.script, 'hex')).hash.toString();
526
- }
527
- catch (err) {
528
- return { error: `mintActions[${i}].mintingPolicyScript is not a valid Plutus script: ${err instanceof Error ? err.message : String(err)}` };
529
- }
530
525
  if (typeof entry.assetUnit !== 'string' || !/^[0-9a-fA-F]*$/.test(entry.assetUnit) || entry.assetUnit.length % 2 !== 0) {
531
526
  return { error: `mintActions[${i}].assetUnit must be hex (policyId+assetName, or a bare assetName)` };
532
527
  }
533
528
  let assetUnit = entry.assetUnit.toLowerCase();
534
- if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
535
- assetUnit = policyId + assetUnit;
529
+ let referenceScript;
530
+ if (hasRef) {
531
+ const ref = entry.referenceScript;
532
+ if (!ref || typeof ref !== 'object' || typeof ref.txHash !== 'string' || !(0, validators_1.isTxHash)(ref.txHash)
533
+ || typeof ref.outputIndex !== 'number' || !Number.isInteger(ref.outputIndex) || ref.outputIndex < 0) {
534
+ return { error: `mintActions[${i}].referenceScript must be {txHash, outputIndex} of the UTxO carrying the policy` };
535
+ }
536
+ referenceScript = { txHash: ref.txHash.toLowerCase(), outputIndex: ref.outputIndex };
537
+ // the policy id is known only once the builder has read the reference script
538
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
539
+ return { error: `mintActions[${i}].assetUnit must be policyId+assetName when the policy is a referenceScript` };
540
+ }
536
541
  }
537
- else if (!assetUnit.startsWith(policyId)) {
538
- return { error: `mintActions[${i}].assetUnit does not start with its policy id ${policyId}` };
542
+ else {
543
+ let policyId;
544
+ try {
545
+ policyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policy.script, 'hex')).hash.toString();
546
+ }
547
+ catch (err) {
548
+ return { error: `mintActions[${i}].mintingPolicyScript is not a valid Plutus script: ${err instanceof Error ? err.message : String(err)}` };
549
+ }
550
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
551
+ assetUnit = policyId + assetUnit;
552
+ }
553
+ else if (!assetUnit.startsWith(policyId)) {
554
+ return { error: `mintActions[${i}].assetUnit does not start with its policy id ${policyId}` };
555
+ }
539
556
  }
540
557
  if (!(0, validators_1.isAssetUnit)(assetUnit))
541
558
  return { error: `mintActions[${i}].assetUnit is not a valid asset unit` };
542
559
  out.push({
543
560
  assetUnit,
544
561
  quantity: BigInt(entry.quantity),
545
- mintingPolicyScript: policy.script,
562
+ ...(policy.script ? { mintingPolicyScript: policy.script } : { referenceScript }),
546
563
  ...(policy.redeemer !== undefined ? { redeemerJson: policy.redeemer } : {}),
547
564
  });
548
565
  }
@@ -322,8 +322,13 @@ export type MintAction = {
322
322
  * top-level mintingPolicyScript. The assetUnit must carry this script's policyId.
323
323
  */
324
324
  mintingPolicyScript?: string;
325
+ /** BuildPlutusTransaction only: UTxO that carries the policy as reference script; exclusive with mintingPolicyScript. */
326
+ referenceScript?: {
327
+ txHash: string;
328
+ outputIndex: number;
329
+ };
325
330
  /**
326
- * Per-action redeemer (parsed PlutusData JSON), only with mintingPolicyScript; falls back to mintRedeemer.
331
+ * Per-action redeemer (parsed PlutusData JSON), only with mintingPolicyScript or referenceScript; falls back to mintRedeemer.
327
332
  * Actions on the same policy must agree (one redeemer per policy in the ledger).
328
333
  */
329
334
  redeemerJson?: JSONValue;