@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20

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 (132) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -3,9 +3,12 @@ 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.BARE_ASSET_STAMP = void 0;
6
7
  exports.mapTransaction = mapTransaction;
7
8
  exports.mapTransactionInputs = mapTransactionInputs;
8
9
  exports.mapTransactionInputAssets = mapTransactionInputAssets;
10
+ exports.mapTransactionCertificates = mapTransactionCertificates;
11
+ exports.mapTransactionWithdrawals = mapTransactionWithdrawals;
9
12
  exports.mapTransactionOutputs = mapTransactionOutputs;
10
13
  exports.mapTransactionOutputAssets = mapTransactionOutputAssets;
11
14
  exports.mapAddress = mapAddress;
@@ -17,8 +20,12 @@ exports.mapNetworkInfo = mapNetworkInfo;
17
20
  exports.mapBlock = mapBlock;
18
21
  exports.mapEpoch = mapEpoch;
19
22
  exports.mapTransactionMetadata = mapTransactionMetadata;
23
+ exports.metadataIdFor = metadataIdFor;
24
+ exports.mapPoolSnapshot = mapPoolSnapshot;
25
+ exports.mapDrepSnapshot = mapDrepSnapshot;
20
26
  exports.mapPool = mapPool;
21
27
  exports.mapAsset = mapAsset;
28
+ exports.mapBareAsset = mapBareAsset;
22
29
  exports.mapAssetHistory = mapAssetHistory;
23
30
  exports.mapDrep = mapDrep;
24
31
  exports.mapAccount = mapAccount;
@@ -31,28 +38,24 @@ exports.mapTransactionSubmission = mapTransactionSubmission;
31
38
  exports.mapAddressSigningRequest = mapAddressSigningRequest;
32
39
  exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
33
40
  exports.normalizeCostModels = normalizeCostModels;
41
+ exports.decodeAssetName = decodeAssetName;
34
42
  exports.computeCip14Fingerprint = computeCip14Fingerprint;
35
43
  exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
44
+ exports.credentialToStakeAddress = credentialToStakeAddress;
45
+ exports.decodeShelleyAddress = decodeShelleyAddress;
46
+ exports.credentialToDrepId = credentialToDrepId;
36
47
  const cds_1 = __importDefault(require("@sap/cds"));
48
+ const node_util_1 = require("node:util");
37
49
  const blake2b_1 = __importDefault(require("blake2b"));
38
50
  const bech32_1 = require("bech32");
39
51
  const client_1 = require("@cardano-ogmios/client");
40
52
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
41
53
  const logger = cds_1.default.log('mappers');
42
54
  const errors_1 = require("./errors");
43
- /**
44
- * Maximum age for cached/indexed data in milliseconds
45
- */
46
- /**
47
- * Map Transaction Data
48
- * Converts provider transaction data into TransactionRow format
49
- * @param providerTx
50
- * @returns {TransactionRow} mapped transaction row
51
- */
55
+ const const_1 = require("./const");
56
+ /** Provider transaction to TransactionRow. */
52
57
  function mapTransaction(providerTx) {
53
- // determine presence of optional data
54
- // length check matters: the Ogmios chain-sync mapper produced `[]` for metadata-less
55
- // txs, which the old `Array.isArray` test counted as "has metadata"
58
+ // length check: chain-sync delivers `[]` for metadata-less txs
56
59
  const hasMetadata = Array.isArray(providerTx.metadata) && providerTx.metadata.length > 0;
57
60
  const hasInputs = Array.isArray(providerTx.inputs) && providerTx.inputs.length > 0;
58
61
  const hasOutputs = Array.isArray(providerTx.outputs) && providerTx.outputs.length > 0;
@@ -71,30 +74,24 @@ function mapTransaction(providerTx) {
71
74
  hasMetadata: hasMetadata,
72
75
  };
73
76
  }
74
- /**
75
- * Map Transaction Inputs
76
- * Converts provider transaction input data into TransactionInputRow format
77
- * @param txHash transaction hash
78
- * @param txInputs transaction inputs from provider
79
- * @returns {TransactionInputRow[]} mapped transaction input rows
80
- */
77
+ /** Provider transaction inputs to TransactionInputRows, keyed by position in the tx. */
81
78
  function mapTransactionInputs(txHash, txInputs) {
82
79
  return txInputs.map((input, idx) => {
83
- // Use array index as the input index (position in this transaction's inputs)
84
- // Note: input.outputIndex is the output index from the ORIGINAL UTxO being spent, not for keying here
80
+ // Position in this tx's inputs; input.outputIndex is the spent UTxO's index, not a key here
85
81
  const inputIndex = idx;
86
- // check presence of address and amount arrays
87
82
  const hasAddress = !!input.address?.length;
88
83
  const hasAssets = Array.isArray(input.amount) && input.amount.length > 0;
89
84
  return {
90
85
  tx_hash: txHash,
91
86
  inputIndex: inputIndex,
92
- // `|| null`: unresolved chain-sync inputs carry '' — persist a null FK, not a
93
- // dangling empty-string Addresses association (lazy-path inputs are never empty)
87
+ // unresolved chain-sync inputs carry '': persist a null FK, not an empty-string association
94
88
  address_address: input.address || null,
95
89
  utxoData_dataHash: input.dataHash || null,
96
90
  utxoData_inlineDatum: input.inlineDatum || null,
97
91
  utxoData_referenceScriptHash: input.referenceScriptHash || null,
92
+ // outpoint of the consumed UTxO
93
+ spentTxHash: input.txHash || null,
94
+ spentOutputIndex: Number.isInteger(input.outputIndex) ? input.outputIndex : null,
98
95
  isCollateral: Boolean(input.isCollateral),
99
96
  isReference: Boolean(input.isReference),
100
97
  hasAddresses: hasAddress,
@@ -102,16 +99,10 @@ function mapTransactionInputs(txHash, txInputs) {
102
99
  };
103
100
  });
104
101
  }
105
- /**
106
- * Map Transaction Input Assets
107
- * Converts provider transaction input asset data into TransactionInputAssetRow format
108
- * @param txHash transaction hash
109
- * @param inputs transaction inputs from provider
110
- * @returns {TransactionInputAssetRow[]} mapped transaction input asset rows
111
- */
102
+ /** Provider transaction input assets to TransactionInputAssetRows. */
112
103
  function mapTransactionInputAssets(txHash, inputs) {
113
104
  return inputs.flatMap((input, idx) => {
114
- // Use array index as the input index (must match mapTransactionInputs)
105
+ // must match mapTransactionInputs
115
106
  const inputIndex = idx;
116
107
  if (!Array.isArray(input.amount))
117
108
  return [];
@@ -128,13 +119,30 @@ function mapTransactionInputAssets(txHash, inputs) {
128
119
  });
129
120
  });
130
121
  }
131
- /**
132
- * Map Transaction Outputs
133
- * Converts provider transaction output data into TransactionOutputRow format
134
- * @param txHash transaction hash
135
- * @param txOutputs transaction outputs from provider
136
- * @returns {TransactionOutputRow[]} mapped transaction output rows
137
- */
122
+ /** Normalized certificates to TransactionCertificateRows, one per (certIndex, kind). */
123
+ function mapTransactionCertificates(txHash, certificates) {
124
+ return certificates.map((c) => ({
125
+ tx_hash: txHash,
126
+ certIndex: c.certIndex,
127
+ kind: c.kind,
128
+ stakeAddress: c.stakeAddress || null,
129
+ poolId: c.poolId || null,
130
+ drepId: c.drepId || null,
131
+ deposit: c.deposit != null ? String(c.deposit) : null,
132
+ epoch: c.epoch ?? null,
133
+ }));
134
+ }
135
+ /** Normalized withdrawals to TransactionWithdrawalRows, one per reward account. */
136
+ function mapTransactionWithdrawals(txHash, withdrawals) {
137
+ return withdrawals
138
+ .filter((w) => !!w.stakeAddress)
139
+ .map((w) => ({
140
+ tx_hash: txHash,
141
+ stakeAddress: w.stakeAddress,
142
+ lovelace: String(w.amount ?? '0'),
143
+ }));
144
+ }
145
+ /** Provider transaction outputs to TransactionOutputRows. */
138
146
  function mapTransactionOutputs(txHash, txOutputs) {
139
147
  return txOutputs.map((output) => {
140
148
  const outputIndex = output.outputIndex;
@@ -152,13 +160,7 @@ function mapTransactionOutputs(txHash, txOutputs) {
152
160
  };
153
161
  });
154
162
  }
155
- /**
156
- * Map Transaction Output Assets
157
- * Converts provider transaction output asset data into TransactionOutputAssetRow format
158
- * @param txHash transaction hash
159
- * @param outputs transaction outputs from provider
160
- * @returns {TransactionOutputAssetRow[]} mapped transaction output asset rows
161
- */
163
+ /** Provider transaction output assets to TransactionOutputAssetRows. */
162
164
  function mapTransactionOutputAssets(txHash, outputs) {
163
165
  return outputs.flatMap((output) => {
164
166
  const outputIndex = output.outputIndex;
@@ -177,13 +179,7 @@ function mapTransactionOutputAssets(txHash, outputs) {
177
179
  });
178
180
  });
179
181
  }
180
- /**
181
- * Map Address Data
182
- * Converts provider address data into AddressRow format
183
- * @param address address string
184
- * @param addressData address data from provider
185
- * @returns {AddressRow} mapped address row
186
- */
182
+ /** Provider address to a temporal AddressRow valid for `maxAge` ms. */
187
183
  function mapAddress(address, addressData, maxAge) {
188
184
  const now = Date.now();
189
185
  const nowIso = new Date(now).toISOString();
@@ -194,7 +190,7 @@ function mapAddress(address, addressData, maxAge) {
194
190
  const utxoCount = Array.isArray(addressData.utxos) ? addressData.utxos.length : 0;
195
191
  const hasUtxos = utxoCount > 0;
196
192
  const hasAssets = Array.isArray(addressData.amount) && addressData.amount.some((a) => a.unit !== 'lovelace');
197
- // Transactions are indexed separately in indexAddress() — updated to true after indexing
193
+ // set to true by indexAddress() once transactions are indexed
198
194
  const hasTransactions = false;
199
195
  return {
200
196
  address,
@@ -210,19 +206,9 @@ function mapAddress(address, addressData, maxAge) {
210
206
  hasTransactions: hasTransactions,
211
207
  };
212
208
  }
213
- /**
214
- * Map Address Transactions
215
- * Converts provider address transaction data into AddressTransactionRow format
216
- * @param addr address string
217
- * @param addressTxsData address transactions data from provider
218
- * @returns {AddressTransactionRow[]} mapped address transaction rows
219
- * */
220
- // AddressTransactions is keyed by (address, tx) and the per-tx net amounts are
221
- // immutable once confirmed — no temporal validity. The entity has no
222
- // validFrom/validTo columns, so the previous TTL plumbing was silently dropped.
209
+ /** Provider transactions to AddressTransactionRows with the address's net amounts; non-temporal. */
223
210
  function mapAddressTransactions(addr, addressTxsData) {
224
211
  return addressTxsData.map((tx) => {
225
- // Calculate net amounts for this address in this transaction
226
212
  const { netLovelace, netAssets } = calculateNetAmounts(addr, tx);
227
213
  return {
228
214
  address_address: addr,
@@ -234,17 +220,11 @@ function mapAddressTransactions(addr, addressTxsData) {
234
220
  };
235
221
  });
236
222
  }
237
- /**
238
- * Calculate net lovelace and asset changes for an address in a transaction
239
- * @param addr the address to calculate for
240
- * @param tx the transaction data
241
- * @returns object with netLovelace and netAssets array
242
- */
223
+ /** Net lovelace and asset changes of an address in a transaction (outputs minus inputs). */
243
224
  function calculateNetAmounts(addr, tx) {
244
225
  let inputLovelace = 0n;
245
226
  let outputLovelace = 0n;
246
227
  const assetBalances = new Map(); // unit -> net quantity
247
- // Process inputs belonging to this address (subtract)
248
228
  for (const input of tx.inputs ?? []) {
249
229
  if (input.address === addr) {
250
230
  for (const amount of input.amount ?? []) {
@@ -252,14 +232,12 @@ function calculateNetAmounts(addr, tx) {
252
232
  inputLovelace += BigInt(amount.quantity || '0');
253
233
  }
254
234
  else {
255
- // Native asset
256
235
  const current = assetBalances.get(amount.unit) || 0n;
257
236
  assetBalances.set(amount.unit, current - BigInt(amount.quantity || '0'));
258
237
  }
259
238
  }
260
239
  }
261
240
  }
262
- // Process outputs going to this address (add)
263
241
  for (const output of tx.outputs ?? []) {
264
242
  if (output.address === addr) {
265
243
  for (const amount of output.amount ?? []) {
@@ -267,19 +245,16 @@ function calculateNetAmounts(addr, tx) {
267
245
  outputLovelace += BigInt(amount.quantity || '0');
268
246
  }
269
247
  else {
270
- // Native asset
271
248
  const current = assetBalances.get(amount.unit) || 0n;
272
249
  assetBalances.set(amount.unit, current + BigInt(amount.quantity || '0'));
273
250
  }
274
251
  }
275
252
  }
276
253
  }
277
- // Convert asset map to array, filtering out zero balances
254
+ // zero balances are dropped
278
255
  const netAssets = [];
279
256
  for (const [unit, quantity] of assetBalances) {
280
257
  if (quantity !== 0n) {
281
- // Parse unit into policyId and assetName
282
- // Format: policyId (56 chars) + assetNameHex
283
258
  const policyId = unit.substring(0, 56);
284
259
  const assetNameHex = unit.substring(56);
285
260
  const assetName = hexToUtf8(assetNameHex);
@@ -297,14 +272,7 @@ function calculateNetAmounts(addr, tx) {
297
272
  netAssets
298
273
  };
299
274
  }
300
- /**
301
- * Map Address UTxOs
302
- * @param addr address string
303
- * @param validFrom validFrom
304
- * @param validTo validTo
305
- * @param addressUtxosData address UTxOs data from provider
306
- * @returns {AddressUTxORow[]} mapped address UTxO rows
307
- */
275
+ /** Provider UTxOs to temporal AddressUTxORows. */
308
276
  function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
309
277
  return addressUtxosData.map((utxo) => {
310
278
  const amounts = Array.isArray(utxo.amount) ? utxo.amount : [];
@@ -317,10 +285,8 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
317
285
  blockHash: utxo.blockHash,
318
286
  utxodata_dataHash: utxo.datumHash,
319
287
  utxodata_inlineDatum: utxo.inlineDatum || null,
320
- // This column is a script HASH (Blake2b256). UTxO.scriptRef is overloaded:
321
- // Blockfrost/Ogmios give a 56-hex hash (stored as-is); Koios gives the full
322
- // script CBOR (used by the tx-builder, but it would truncate this hash
323
- // column) — only persist hash-length values here.
288
+ // Hash column: Blockfrost/Ogmios give a 56-hex hash, Koios the full script CBOR, so only
289
+ // hash-length values are persisted
324
290
  utxodata_referenceScriptHash: utxo.scriptRef && utxo.scriptRef.length <= 64 ? utxo.scriptRef : null,
325
291
  lovelace: lovelace,
326
292
  validFrom: validFrom,
@@ -329,15 +295,7 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
329
295
  };
330
296
  });
331
297
  }
332
- /**
333
- * Map Address Assets
334
- * Converts provider address asset data into AddressAssetRow format
335
- * @param addr address string
336
- * @param validFrom validFrom
337
- * @param validTo validTo
338
- * @param AssetAssets address assets from provider
339
- * @returns {AddressAssetRow[]} mapped address asset rows
340
- */
298
+ /** Provider address amounts (without lovelace) to temporal AddressAssetRows. */
341
299
  function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
342
300
  return AssetAssets
343
301
  .filter((asset) => asset.unit !== 'lovelace')
@@ -354,14 +312,7 @@ function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
354
312
  };
355
313
  });
356
314
  }
357
- /**
358
- * Map UTxO Assets
359
- * Converts provider address UTxO asset data into UTxOAssetRow format
360
- * @param addressUtxosData address UTxOs data from provider
361
- * @param validFrom validFrom
362
- * @param validTo validTo
363
- * @returns {UTxOAssetRow[]} mapped UTxO asset rows
364
- */
315
+ /** Native assets of provider UTxOs to temporal UTxOAssetRows. */
365
316
  function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
366
317
  const assets = [];
367
318
  addressUtxosData.forEach((utxo) => {
@@ -385,12 +336,7 @@ function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
385
336
  });
386
337
  return assets;
387
338
  }
388
- /**
389
- * Map Network Information
390
- * Converts provider network information data into NetworkInfoRow format
391
- * @param providerNetworkData
392
- * @returns {NetworkInfoRow} mapped network information row
393
- */
339
+ /** Provider network information to a temporal NetworkInfoRow. */
394
340
  function mapNetworkInfo(providerNetworkData, max_age, network) {
395
341
  const now = Date.now();
396
342
  const nowIso = new Date(now).toISOString();
@@ -409,23 +355,16 @@ function mapNetworkInfo(providerNetworkData, max_age, network) {
409
355
  activeStake: providerNetworkData.stake.active,
410
356
  };
411
357
  }
412
- /**
413
- * Map Block Data
414
- * Converts provider block data into BlockRow format
415
- * @param providerBlockData block data from provider
416
- * @param epochData epoch data for the block's epoch
417
- * @returns {BlockRow} mapped block row
418
- */
358
+ /** Provider block to BlockRow. */
419
359
  function mapBlock(providerBlockData, epochData) {
420
360
  return {
421
361
  time: new Date(providerBlockData.time * 1000).toISOString(),
422
362
  height: providerBlockData.height,
423
363
  hash: providerBlockData.hash,
424
- // was `String(x ?? null)` → persisted the literal string "null" when absent
425
364
  slotLeader: providerBlockData.slotLeader ?? null,
426
365
  epochNumber: epochData?.epoch ?? providerBlockData.epoch,
427
366
  epoch: epochData,
428
- // absolute slot — the crawler's reorg cut axis (same axis as Transactions.slot)
367
+ // absolute slot: the crawler's reorg cut axis (same as Transactions.slot)
429
368
  slot: providerBlockData.slot ?? null,
430
369
  epochSlot: providerBlockData.epochSlot,
431
370
  size: providerBlockData.size,
@@ -433,12 +372,7 @@ function mapBlock(providerBlockData, epochData) {
433
372
  fees: providerBlockData.fees ?? '0',
434
373
  };
435
374
  }
436
- /**
437
- * Map Epoch Data
438
- * Converts provider epoch data into EpochRow format
439
- * @param providerEpochData epoch data from provider
440
- * @returns {EpochRow} mapped epoch row
441
- */
375
+ /** Provider epoch to EpochRow. */
442
376
  function mapEpoch(providerEpochData) {
443
377
  return {
444
378
  epoch: providerEpochData.epoch,
@@ -453,44 +387,86 @@ function mapEpoch(providerEpochData) {
453
387
  activeStake: providerEpochData.active_stake,
454
388
  };
455
389
  }
456
- /**
457
- * Map Transaction Metadata
458
- * Converts provider transaction metadata labels into TransactionMetadataRow format
459
- * @param providerLabels array of metadata label data from provider
460
- * @returns {TransactionMetadataRow[]} mapped transaction metadata rows
461
- */
390
+ /** Provider metadata labels to TransactionMetadataRows; non-uint64 labels are skipped. */
462
391
  function mapTransactionMetadata(providerLabels) {
463
392
  const rows = [];
464
393
  for (const lbl of providerLabels) {
465
- const numericId = Number(lbl.label);
466
- // Metadata labels are uint64; the exact value is kept in the `label` string.
467
- // The numeric `id` key (now Integer64) is exact up to 2^53 — warn beyond that.
468
- if (!Number.isSafeInteger(numericId)) {
469
- logger.warn(`Metadata label ${lbl.label} exceeds safe-integer range — numeric id key may lose precision (string label is exact)`);
394
+ const id = metadataIdFor(lbl.label);
395
+ if (id === null) {
396
+ // a NaN key would fail the whole bulk write on PostgreSQL
397
+ logger.warn(`Metadata label ${JSON.stringify(lbl.label)} of tx ${lbl.txHash} is not a uint64 — row skipped`);
398
+ continue;
470
399
  }
471
400
  rows.push({
472
- id: numericId,
401
+ // exact int64 key (see metadataIdFor); `label` keeps the original string
402
+ id: id,
473
403
  tx_hash: lbl.txHash,
474
404
  label: lbl.label.toString(),
475
- // Ogmios' parser deliberately exposes numeric metadata as native bigint.
476
- // Its matching serializer writes those values as exact JSON number tokens;
477
- // native JSON.stringify would throw, while Number coercion would truncate.
405
+ // Ogmios exposes numeric metadata as bigint; safeJSON writes exact number tokens
478
406
  payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
479
407
  });
480
408
  }
481
409
  return rows;
482
410
  }
483
411
  /**
484
- * Map Pool Data
485
- * Converts provider pool data into PoolRow format
486
- * @param providerPoolData pool data from provider
487
- * @returns {PoolRow} mapped pool row
412
+ * uint64 metadata label to the int64 `TransactionMetadata.id` key: labels >= 2^63 wrap via two's complement,
413
+ * values beyond 2^53 are passed as a decimal string (CAP accepts strings for Integer64).
414
+ * @returns the key, or null when the label is not a non-negative integer
488
415
  */
416
+ function metadataIdFor(label) {
417
+ let big;
418
+ if (typeof label === 'number') {
419
+ if (!Number.isFinite(label))
420
+ return null;
421
+ big = BigInt(Math.trunc(label));
422
+ }
423
+ else {
424
+ const text = String(label).trim();
425
+ if (!/^\d+$/.test(text))
426
+ return null;
427
+ big = BigInt(text);
428
+ }
429
+ const wrapped = BigInt.asIntN(64, big);
430
+ const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
431
+ return safe ? Number(wrapped) : wrapped.toString();
432
+ }
433
+ /** Pool observation at an epoch boundary to a non-temporal PoolEpochSnapshotRow dated by (epoch, snapshotSlot). */
434
+ function mapPoolSnapshot(providerPoolData, epoch, at) {
435
+ return {
436
+ poolId: providerPoolData.poolId,
437
+ epoch,
438
+ snapshotSlot: at.slot,
439
+ snapshotTime: at.time,
440
+ blocksMinted: providerPoolData.blocksMinted,
441
+ blocksEpoch: providerPoolData.blocksEpoch,
442
+ liveStake: providerPoolData.liveStake,
443
+ liveSize: Number(providerPoolData.liveSize),
444
+ liveSaturation: Number(providerPoolData.liveSaturation),
445
+ liveDelegators: providerPoolData.liveDelegators,
446
+ activeStake: providerPoolData.activeStake,
447
+ activeSize: Number(providerPoolData.activeSize),
448
+ pledge: providerPoolData.pledge,
449
+ margin: Number(providerPoolData.margin),
450
+ fixedCost: providerPoolData.fixedCost,
451
+ };
452
+ }
453
+ /** DRep observation at an epoch boundary to a non-temporal DrepEpochSnapshotRow. */
454
+ function mapDrepSnapshot(providerDrepData, epoch, at) {
455
+ return {
456
+ drepId: providerDrepData.drepId,
457
+ epoch,
458
+ snapshotSlot: at.slot,
459
+ snapshotTime: at.time,
460
+ amount: providerDrepData.amount,
461
+ hasScript: providerDrepData.hasScript,
462
+ lastActiveEpoch: providerDrepData.lastActiveEpoch,
463
+ retired: providerDrepData.retired,
464
+ expired: providerDrepData.expired,
465
+ };
466
+ }
467
+ /** Provider pool to a temporal PoolRow valid for `max_age` ms. */
489
468
  function mapPool(providerPoolData, max_age) {
490
- // temporal stamping: live fields (liveStake/liveSaturation/retired…) change every
491
- // epoch, so a slice expires after max_age and the index-on-miss read re-fetches.
492
- // Read the clock ONCE — separate Date.now() calls for validFrom/validTo let the
493
- // millisecond tick over between them, making the span max_age+1.
469
+ // one clock read, so validTo - validFrom is exactly max_age
494
470
  const now = Date.now();
495
471
  const validFrom = new Date(now).toISOString();
496
472
  const validTo = new Date(now + max_age).toISOString();
@@ -513,17 +489,9 @@ function mapPool(providerPoolData, max_age) {
513
489
  validTo,
514
490
  };
515
491
  }
516
- /**
517
- * Map Asset Info Data
518
- * Converts provider asset info into AssetRow format. Provider data is already
519
- * normalized by the backend mapper into the canonical AssetInfo shape, so this
520
- * function just stamps temporal validity and JSON-stringifies the on-chain metadata.
521
- * @param providerAssetInfo canonical asset info from backend
522
- * @param max_age TTL window in ms for the temporal validity
523
- * @returns {AssetRow} mapped asset row
524
- */
492
+ /** Canonical asset info to a temporal AssetRow valid for `max_age` ms; on-chain metadata is JSON-stringified. */
525
493
  function mapAsset(providerAssetInfo, max_age) {
526
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
494
+ // one clock read (see mapPool)
527
495
  const now = Date.now();
528
496
  const validFrom = new Date(now).toISOString();
529
497
  const validTo = new Date(now + max_age).toISOString();
@@ -551,11 +519,45 @@ function mapAsset(providerAssetInfo, max_age) {
551
519
  };
552
520
  }
553
521
  /**
554
- * Map Asset History entries to row format. No temporal stamping — mint/burn
555
- * events are immutable; UPSERT keyed on (unit, txHash) is idempotent.
556
- * @param entries asset history events from backend (already canonical)
557
- * @returns {AssetHistoryRow[]} mapped rows
522
+ * Fixed validity stamp for a crawler-written bare `Assets` row: epoch zero, so the row is born expired
523
+ * (hidden by CAP's temporal filter) and its `(validFrom, unit)` key never collides with a mapAsset() slice.
558
524
  */
525
+ exports.BARE_ASSET_STAMP = '1970-01-01T00:00:00.000Z';
526
+ /**
527
+ * Bare AssetRow from the unit alone (policyId, assetNameHex, decoded name, CIP-14 fingerprint), no provider call.
528
+ * Stamped `validTo === validFrom` with the fixed sentinel: hidden from OData reads, so the first keyed read
529
+ * still misses and the lazy path enriches it; one idempotent row per unit inside the crawler's block tx.
530
+ * @returns the row, or null when the unit is not a native asset unit
531
+ */
532
+ function mapBareAsset(unit) {
533
+ // same unit definition isAssetUnit() enforces on the API
534
+ if (!const_1.ASSET_UNIT_REGEX.test(unit))
535
+ return null;
536
+ const policyId = unit.slice(0, 56);
537
+ const assetNameHex = unit.slice(56);
538
+ return {
539
+ unit,
540
+ policyId,
541
+ assetNameHex,
542
+ // hex fallback for non-text and NUL-bearing names
543
+ assetName: assetNameHex.length > 0 ? decodeAssetName(assetNameHex) : '',
544
+ fingerprint: computeCip14Fingerprint(policyId, assetNameHex),
545
+ totalSupply: null,
546
+ mintOrBurnCount: null,
547
+ initialMintTxHash: null,
548
+ initialMintTime: null,
549
+ onchainMetadata: null,
550
+ registryName: null,
551
+ registryTicker: null,
552
+ registryDecimals: null,
553
+ registryDescription: null,
554
+ registryUrl: null,
555
+ registryLogo: null,
556
+ validFrom: exports.BARE_ASSET_STAMP,
557
+ validTo: exports.BARE_ASSET_STAMP,
558
+ };
559
+ }
560
+ /** Asset history events to non-temporal AssetHistoryRows (immutable, keyed on unit + txHash). */
559
561
  function mapAssetHistory(entries) {
560
562
  return entries.map((e) => ({
561
563
  unit: e.unit,
@@ -566,16 +568,9 @@ function mapAssetHistory(entries) {
566
568
  blockHeight: e.blockHeight,
567
569
  }));
568
570
  }
569
- /**
570
- * Map Drep Data
571
- * Converts provider drep data into DrepRow format
572
- * @param providerDrepData drep data from provider
573
- * @returns {DrepRow} mapped drep row
574
- */
571
+ /** Provider DRep to a temporal DrepRow valid for `max_age` ms. */
575
572
  function mapDrep(providerDrepData, max_age) {
576
- // temporal stamping: amount/retired/expired drift over time → slice expires
577
- // after max_age so the index-on-miss read re-fetches fresh state.
578
- // Read the clock once so the span is exactly max_age (see mapPool).
573
+ // one clock read (see mapPool)
579
574
  const now = Date.now();
580
575
  const validFrom = new Date(now).toISOString();
581
576
  const validTo = new Date(now + max_age).toISOString();
@@ -591,14 +586,9 @@ function mapDrep(providerDrepData, max_age) {
591
586
  validTo,
592
587
  };
593
588
  }
594
- /**
595
- * Map Account Data
596
- * Converts provider account data into AccountRow format
597
- * @param providerAccountData account data from provider
598
- * @returns {AccountRow} mapped account row
599
- */
589
+ /** Provider account to a temporal AccountRow valid for `max_age` ms. */
600
590
  function mapAccount(providerAccountData, max_age) {
601
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
591
+ // one clock read (see mapPool)
602
592
  const now = Date.now();
603
593
  const validFrom = new Date(now).toISOString();
604
594
  const validTo = new Date(now + max_age).toISOString();
@@ -617,32 +607,19 @@ function mapAccount(providerAccountData, max_age) {
617
607
  hasAddresses: providerAccountData.addresses.length > 0,
618
608
  };
619
609
  }
620
- /**
621
- * Map Backend Error
622
- * Converts BackendError or unknown error into OData request rejection
623
- * @param req OData request
624
- * @param err error object (BackendError or unknown)
625
- * @param ctx context string for error message
626
- */
610
+ /** Rejects the OData request for a BackendError; unknown errors are logged and answered as a sanitized 500. */
627
611
  function mapError(req, err, ctx) {
628
612
  if (err instanceof errors_1.BackendError) {
629
613
  return req.reject(err.statusCode, fmt(err.code, ctx, err.message), err.target);
630
614
  }
631
- // Handle non-BackendError (plain Error, string, etc.)
632
- // Log full error server-side, but return sanitized message to client
633
615
  const internalMsg = err instanceof Error ? err.message : String(err);
634
616
  logger.error({ error: internalMsg }, `Unexpected error in ${ctx}`);
635
617
  return req.reject(500, fmt('INTERNAL_ERROR', ctx, 'An internal error occurred'));
636
618
  }
637
- /**
638
- * Map Transaction Build Result
639
- * Converts provider transaction build result into TransactionBuildRow format
640
- * @param txbuildResult transaction build result from provider
641
- * @returns {TransactionBuildRow} mapped transaction build row
642
- */
619
+ /** Build result to a temporal TransactionBuildRow with a fresh build id. */
643
620
  function mapBuildResult(txbuildResult, max_age) {
644
621
  const buildId = cds_1.default.utils.uuid();
645
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
622
+ // one clock read (see mapPool)
646
623
  const nowMs = Date.now();
647
624
  const now = Math.floor(nowMs / 1000);
648
625
  const validFrom = new Date(nowMs).toISOString();
@@ -660,25 +637,19 @@ function mapBuildResult(txbuildResult, max_age) {
660
637
  unsignedTxCbor: txbuildResult.unsignedTxCbor,
661
638
  txBodyHash: txbuildResult.txBodyHash,
662
639
  fee: txbuildResult.feeLovelace,
663
- size: txbuildResult.sizeBytes, // size in bytes
640
+ size: txbuildResult.sizeBytes, // bytes
664
641
  createdAt: now, // epoch seconds
665
642
  submission: null,
666
- hasInputs: hasInputs, // indicates if build has inputs
667
- hasOutputs: hasOutputs, // indicates if build has outputs
668
- wasSubmitted: false, // indicates if this build was submitted
643
+ hasInputs: hasInputs,
644
+ hasOutputs: hasOutputs,
645
+ wasSubmitted: false,
669
646
  scriptHash: txbuildResult.scriptHash ?? null,
670
647
  mintScriptHash: txbuildResult.mintScriptHash ?? null,
671
648
  forcedInputsUsed: txbuildResult.forcedInputsUsed ?? 0,
672
649
  referenceInputsUsed: txbuildResult.referenceInputsUsed ?? 0,
673
650
  };
674
651
  }
675
- /**
676
- * Map Transaction Build Inputs
677
- * Converts transaction build result inputs into TransactionBuildInputRow format
678
- * @param buildId the transaction build ID
679
- * @param inputs transaction build result inputs
680
- * @returns {TransactionBuildInputRow[]} mapped transaction build input rows
681
- */
652
+ /** Build result inputs to TransactionBuildInputRows. */
682
653
  function mapBuildInputs(buildId, inputs) {
683
654
  return inputs.map((input, idx) => ({
684
655
  build_id: buildId,
@@ -690,14 +661,7 @@ function mapBuildInputs(buildId, inputs) {
690
661
  hasAssets: false, // simple ADA transfers don't have assets
691
662
  }));
692
663
  }
693
- /**
694
- * Map Transaction Build Outputs
695
- * Converts transaction build result outputs into TransactionBuildOutputRow format
696
- * @param buildId the transaction build ID
697
- * @param outputs transaction build result outputs
698
- * @param changeAddress the change address to identify change outputs
699
- * @returns {TransactionBuildOutputRow[]} mapped transaction build output rows
700
- */
664
+ /** Build result outputs to TransactionBuildOutputRows; `changeAddress` marks the change output. */
701
665
  function mapBuildOutputs(buildId, outputs, changeAddress) {
702
666
  return outputs.map((output, idx) => ({
703
667
  build_id: buildId,
@@ -708,12 +672,7 @@ function mapBuildOutputs(buildId, outputs, changeAddress) {
708
672
  hasAssets: false, // simple ADA transfers don't have assets
709
673
  }));
710
674
  }
711
- /**
712
- * Map Protocol Parameters
713
- * Converts provider protocol parameters into ProtocolParameterRow format
714
- * @param providerParams protocol parameters from provider
715
- * @returns {ProtocolParameterRow} mapped protocol parameter row
716
- */
675
+ /** Provider protocol parameters to ProtocolParameterRow. */
717
676
  function mapProtocolParameters(providerParams) {
718
677
  return {
719
678
  network: providerParams.network,
@@ -752,13 +711,7 @@ function mapProtocolParameters(providerParams) {
752
711
  source: providerParams.source,
753
712
  };
754
713
  }
755
- /**
756
- * Map Transaction Submission
757
- * Converts signed transaction CBOR and hash into TransactionSubmissionRow format
758
- * @param signedTxCbor signed transaction in CBOR hex format
759
- * @param txHash transaction hash
760
- * @returns {TransactionSubmissionRow} mapped transaction submission row
761
- */
714
+ /** Signed tx CBOR and hash to a TransactionSubmissionRow stamped now (epoch seconds). */
762
715
  function mapTransactionSubmission(signedTxCbor, txHash) {
763
716
  const now = Math.floor(Date.now() / 1000);
764
717
  return {
@@ -767,26 +720,14 @@ function mapTransactionSubmission(signedTxCbor, txHash) {
767
720
  submittedAt: now,
768
721
  };
769
722
  }
770
- /**
771
- * Map Address Signing Requests
772
- * Creates AddressSigningRequest row for address-signing request association
773
- * @param addr bech32 address
774
- * @param signingRequestId signing request UUID
775
- * @returns {AddressSigningRequestRow} mapped address signing request row
776
- */
723
+ /** Address to signing-request association row. */
777
724
  function mapAddressSigningRequest(addr, signingRequestId) {
778
725
  return {
779
726
  address_address: addr,
780
727
  signingRequest_id: signingRequestId,
781
728
  };
782
729
  }
783
- /**
784
- * Map Address Transaction Builds
785
- * Creates AddressTransactionBuild row for address-build association
786
- * @param addr bech32 address
787
- * @param buildId transaction build UUID
788
- * @returns {AddressTransactionBuildRow} mapped address transaction build row
789
- */
730
+ /** Address to transaction-build association row. */
790
731
  function mapAddressTransactionBuild(addr, buildId) {
791
732
  return {
792
733
  address_address: addr,
@@ -797,19 +738,8 @@ function mapAddressTransactionBuild(addr, buildId) {
797
738
  // Helper Functions
798
739
  //-----------------------------------------------------------------------
799
740
  /**
800
- * Normalize cost models to array format in canonical Plutus parameter order.
801
- *
802
- * Blockfrost's cost_models (named keys) has known key-value mapping bugs for
803
- * PlutusV3 (shifted values in the quotientInteger/remainderInteger region).
804
- * The Blockfrost backend now prefers cost_models_raw (canonical arrays from the
805
- * node) which bypasses this issue entirely.
806
- *
807
- * For V3 arrays: already in canonical order, just pad to 297 via toCostModelArrV3.
808
- * For V3 objects (Ogmios named format): toCostModelArrV3(obj) maps via canonical keys.
809
- * For V1/V2: alphabetical order IS the canonical order (no reordering needed).
810
- *
811
- * @param raw - Raw cost models from any backend (Blockfrost, Ogmios, Koios)
812
- * @returns Object with all cost model values as number arrays in canonical order
741
+ * Cost models to number arrays in canonical Plutus parameter order. V3 goes through toCostModelArrV3
742
+ * (canonical keys, padded to 297); for V1/V2 alphabetical key order is the canonical order.
813
743
  */
814
744
  function normalizeCostModels(raw) {
815
745
  const result = {};
@@ -817,12 +747,10 @@ function normalizeCostModels(raw) {
817
747
  const isV3 = key === 'PlutusV3' || key === 'plutus:v3';
818
748
  if (Array.isArray(value)) {
819
749
  if (isV3) {
820
- // V3 arrays (from cost_models_raw or Ogmios) are already in canonical Plutus V3 order.
821
- // toCostModelArrV3 pads to 297 (Chang 2) with defaults if the array is shorter.
750
+ // already canonical; toCostModelArrV3 pads short arrays to 297 with defaults
822
751
  result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(value)).map(Number);
823
752
  }
824
753
  else {
825
- // V1/V2: pass through (already in canonical order)
826
754
  result[key] = value;
827
755
  }
828
756
  }
@@ -832,7 +760,6 @@ function normalizeCostModels(raw) {
832
760
  result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(obj)).map(Number);
833
761
  }
834
762
  else {
835
- // V1/V2: alphabetical sort IS correct for those versions
836
763
  result[key] = Object.keys(obj).sort()
837
764
  .map(k => obj[k]);
838
765
  }
@@ -840,25 +767,29 @@ function normalizeCostModels(raw) {
840
767
  }
841
768
  return result;
842
769
  }
770
+ /** Hex to UTF-8 display string, hex fallback (see decodeAssetName). */
771
+ function hexToUtf8(hex) {
772
+ return decodeAssetName(hex);
773
+ }
774
+ // ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the round trip
775
+ const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
843
776
  /**
844
- * Convert hex string to UTF-8 string, falling back to hex if conversion fails.
845
- * This helper reduces code duplication and improves performance by centralizing
846
- * the conversion logic.
847
- *
848
- * @param hex - Hexadecimal string to convert
849
- * @returns {string} UTF-8 string or original hex if conversion fails
777
+ * Asset name (hex bytes) to its display string; the hex is returned unchanged for invalid UTF-8 or
778
+ * names containing U+0000 (PostgreSQL rejects NUL in `text`). `assetNameHex` always keeps the exact bytes.
850
779
  */
851
- function hexToUtf8(hex) {
780
+ function decodeAssetName(hex) {
852
781
  if (!hex)
853
782
  return hex;
854
- return Buffer.from(hex, 'hex').toString('utf8');
783
+ let text;
784
+ try {
785
+ text = strictUtf8.decode(Buffer.from(hex, 'hex'));
786
+ }
787
+ catch {
788
+ return hex;
789
+ }
790
+ return text.includes('\u0000') ? hex : text;
855
791
  }
856
- /**
857
- * Parse asset unit (policyId + assetNameHex) into components.
858
- * Optimizes repeated parsing logic across multiple mapper functions.
859
- * @param unit - Asset unit string (56 char policyId + asset name hex)
860
- * @returns { policyId: string | null; assetName: string | null } Object with policyId and assetName
861
- */
792
+ /** Split an asset unit into policyId and decoded assetName; `lovelace` and malformed units get a null policyId. */
862
793
  function parseAssetUnit(unit) {
863
794
  if (unit === 'lovelace') {
864
795
  return { policyId: null, assetName: 'lovelace' };
@@ -871,13 +802,7 @@ function parseAssetUnit(unit) {
871
802
  const assetName = assetNameHex.length > 0 ? hexToUtf8(assetNameHex) : '';
872
803
  return { policyId, assetName };
873
804
  }
874
- /**
875
- * Compute CIP-14 asset fingerprint from policyId and assetName.
876
- * Algorithm: bech32_encode("asset", blake2b_160(policyId_bytes + assetName_bytes))
877
- * @param policyIdHex - Policy ID as hex string (56 chars / 28 bytes)
878
- * @param assetNameHex - Asset name as hex string (variable length)
879
- * @returns CIP-14 fingerprint string (e.g. "asset1...")
880
- */
805
+ /** CIP-14 fingerprint: bech32("asset", blake2b_160(policyId_bytes + assetName_bytes)). */
881
806
  function computeCip14Fingerprint(policyIdHex, assetNameHex) {
882
807
  const input = Buffer.from(policyIdHex + assetNameHex, 'hex');
883
808
  const out = Buffer.alloc(20);
@@ -885,11 +810,7 @@ function computeCip14Fingerprint(policyIdHex, assetNameHex) {
885
810
  const words = bech32_1.bech32.toWords(out);
886
811
  return bech32_1.bech32.encode('asset', words);
887
812
  }
888
- /**
889
- * Derive an enterprise script address from a script hash and network.
890
- * Enterprise address = header_byte + 28-byte script hash, bech32-encoded.
891
- * Header: 0x71 (mainnet, type 7 network 1) or 0x70 (testnet, type 7 network 0).
892
- */
813
+ /** Enterprise script address: header 0x71 (mainnet) / 0x70 (testnet) + 28-byte script hash, bech32. */
893
814
  function scriptHashToEnterpriseAddress(scriptHashHex, network) {
894
815
  const headerByte = network === 'mainnet' ? 0x71 : 0x70;
895
816
  const payload = Buffer.alloc(29);
@@ -899,13 +820,71 @@ function scriptHashToEnterpriseAddress(scriptHashHex, network) {
899
820
  const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
900
821
  return bech32_1.bech32.encode(hrp, words, 120);
901
822
  }
902
- /**
903
- * Format error message
904
- * @param code error code
905
- * @param ctx context string
906
- * @param msg error message
907
- * @returns {string} formatted error message
908
- */
823
+ /** Stake credential to bech32 reward account; header nibbles 0xe key / 0xf script, network 1 mainnet / 0 testnets. */
824
+ function credentialToStakeAddress(credentialHex, isScript, network) {
825
+ const header = (isScript ? 0xf0 : 0xe0) | (network === 'mainnet' ? 0x01 : 0x00);
826
+ const payload = Buffer.alloc(29);
827
+ payload[0] = header;
828
+ Buffer.from(credentialHex, 'hex').copy(payload, 1);
829
+ const hrp = network === 'mainnet' ? 'stake' : 'stake_test';
830
+ return bech32_1.bech32.encode(hrp, bech32_1.bech32.toWords(payload), 120);
831
+ }
832
+ /**
833
+ * Decode the CIP-19 Shelley address header: type, script flag and, for base addresses, the embedded
834
+ * stake credential as a reward account. Byron (base58) and unparseable input yield `byron` / `unknown`.
835
+ */
836
+ function decodeShelleyAddress(address) {
837
+ const none = { type: 'unknown', isScript: false, stakeAddress: null, networkId: null };
838
+ if (typeof address !== 'string' || !address.length)
839
+ return none;
840
+ let bytes;
841
+ try {
842
+ const decoded = bech32_1.bech32.decode(address, 120);
843
+ if (decoded.prefix !== 'addr' && decoded.prefix !== 'addr_test' && decoded.prefix !== 'stake' && decoded.prefix !== 'stake_test')
844
+ return none;
845
+ bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
846
+ }
847
+ catch {
848
+ // Byron addresses are base58 and start with Ae2 / DdzFF (mainnet) or 2cWKM… (testnets)
849
+ return /^(Ae2|DdzFF|2cWKM|37btj|KjgoiX)/.test(address) ? { ...none, type: 'byron' } : none;
850
+ }
851
+ if (!bytes.length)
852
+ return none;
853
+ const header = bytes[0];
854
+ const type = header >> 4;
855
+ const networkId = header & 0x0f;
856
+ const net = networkId === 1 ? 'mainnet' : 'preview';
857
+ switch (type) {
858
+ case 0:
859
+ case 1:
860
+ case 2:
861
+ case 3: {
862
+ const stakeAddress = bytes.length >= 57
863
+ ? credentialToStakeAddress(bytes.subarray(29, 57).toString('hex'), type >= 2, net)
864
+ : null;
865
+ return { type: 'base', isScript: type === 1 || type === 3, stakeAddress, networkId };
866
+ }
867
+ case 4:
868
+ case 5:
869
+ return { type: 'pointer', isScript: type === 5, stakeAddress: null, networkId };
870
+ case 6:
871
+ case 7:
872
+ return { type: 'enterprise', isScript: type === 7, stakeAddress: null, networkId };
873
+ case 14:
874
+ case 15:
875
+ return { type: 'reward', isScript: type === 15, stakeAddress: address, networkId };
876
+ default:
877
+ return { ...none, networkId };
878
+ }
879
+ }
880
+ /** DRep credential to CIP-129 DRep ID (29 bytes): header 0x22 key hash / 0x23 script hash. */
881
+ function credentialToDrepId(credentialHex, isScript) {
882
+ const payload = Buffer.alloc(29);
883
+ payload[0] = isScript ? 0x23 : 0x22;
884
+ Buffer.from(credentialHex, 'hex').copy(payload, 1);
885
+ return bech32_1.bech32.encode('drep', bech32_1.bech32.toWords(payload), 120);
886
+ }
887
+ /** `[code] ctx: msg` */
909
888
  function fmt(code, ctx, msg) {
910
889
  return `[${code}] ${ctx}: ${msg}`;
911
890
  }