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

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 (138) 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 +231 -6
  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 +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -3,9 +3,13 @@ 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 = exports.TX_SEQ_SLOT_FACTOR = void 0;
7
+ exports.txSeqOf = txSeqOf;
6
8
  exports.mapTransaction = mapTransaction;
7
9
  exports.mapTransactionInputs = mapTransactionInputs;
8
10
  exports.mapTransactionInputAssets = mapTransactionInputAssets;
11
+ exports.mapTransactionCertificates = mapTransactionCertificates;
12
+ exports.mapTransactionWithdrawals = mapTransactionWithdrawals;
9
13
  exports.mapTransactionOutputs = mapTransactionOutputs;
10
14
  exports.mapTransactionOutputAssets = mapTransactionOutputAssets;
11
15
  exports.mapAddress = mapAddress;
@@ -17,8 +21,12 @@ exports.mapNetworkInfo = mapNetworkInfo;
17
21
  exports.mapBlock = mapBlock;
18
22
  exports.mapEpoch = mapEpoch;
19
23
  exports.mapTransactionMetadata = mapTransactionMetadata;
24
+ exports.metadataIdFor = metadataIdFor;
25
+ exports.mapPoolSnapshot = mapPoolSnapshot;
26
+ exports.mapDrepSnapshot = mapDrepSnapshot;
20
27
  exports.mapPool = mapPool;
21
28
  exports.mapAsset = mapAsset;
29
+ exports.mapBareAsset = mapBareAsset;
22
30
  exports.mapAssetHistory = mapAssetHistory;
23
31
  exports.mapDrep = mapDrep;
24
32
  exports.mapAccount = mapAccount;
@@ -31,33 +39,35 @@ exports.mapTransactionSubmission = mapTransactionSubmission;
31
39
  exports.mapAddressSigningRequest = mapAddressSigningRequest;
32
40
  exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
33
41
  exports.normalizeCostModels = normalizeCostModels;
42
+ exports.decodeAssetName = decodeAssetName;
34
43
  exports.computeCip14Fingerprint = computeCip14Fingerprint;
35
44
  exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
45
+ exports.credentialToStakeAddress = credentialToStakeAddress;
46
+ exports.decodeShelleyAddress = decodeShelleyAddress;
47
+ exports.credentialToDrepId = credentialToDrepId;
36
48
  const cds_1 = __importDefault(require("@sap/cds"));
49
+ const node_util_1 = require("node:util");
37
50
  const blake2b_1 = __importDefault(require("blake2b"));
38
51
  const bech32_1 = require("bech32");
39
52
  const client_1 = require("@cardano-ogmios/client");
40
53
  const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
41
54
  const logger = cds_1.default.log('mappers');
42
55
  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
- */
56
+ const const_1 = require("./const");
57
+ /** Key of a transaction's input/output rows: chain position, ascending, below 2^53 for any real slot. */
58
+ exports.TX_SEQ_SLOT_FACTOR = 65536;
59
+ function txSeqOf(slot, txIndex) {
60
+ return slot * exports.TX_SEQ_SLOT_FACTOR + txIndex;
61
+ }
62
+ /** Provider transaction to TransactionRow. */
52
63
  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"
64
+ // length check: chain-sync delivers `[]` for metadata-less txs
56
65
  const hasMetadata = Array.isArray(providerTx.metadata) && providerTx.metadata.length > 0;
57
66
  const hasInputs = Array.isArray(providerTx.inputs) && providerTx.inputs.length > 0;
58
67
  const hasOutputs = Array.isArray(providerTx.outputs) && providerTx.outputs.length > 0;
59
68
  return {
60
69
  hash: providerTx.hash,
70
+ txSeq: txSeqOf(providerTx.slot, providerTx.index),
61
71
  blockHash: providerTx.blockHash,
62
72
  blockHeight: providerTx.blockHeight ?? null,
63
73
  blockTime: providerTx.blockTime ?? null,
@@ -71,30 +81,24 @@ function mapTransaction(providerTx) {
71
81
  hasMetadata: hasMetadata,
72
82
  };
73
83
  }
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
- */
81
- function mapTransactionInputs(txHash, txInputs) {
84
+ /** Provider transaction inputs to TransactionInputRows, keyed by position in the tx. */
85
+ function mapTransactionInputs(txSeq, txInputs) {
82
86
  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
87
+ // Position in this tx's inputs; input.outputIndex is the spent UTxO's index, not a key here
85
88
  const inputIndex = idx;
86
- // check presence of address and amount arrays
87
89
  const hasAddress = !!input.address?.length;
88
90
  const hasAssets = Array.isArray(input.amount) && input.amount.length > 0;
89
91
  return {
90
- tx_hash: txHash,
92
+ txSeq,
91
93
  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)
94
+ // unresolved chain-sync inputs carry '': persist a null FK, not an empty-string association
94
95
  address_address: input.address || null,
95
96
  utxoData_dataHash: input.dataHash || null,
96
97
  utxoData_inlineDatum: input.inlineDatum || null,
97
98
  utxoData_referenceScriptHash: input.referenceScriptHash || null,
99
+ // outpoint of the consumed UTxO
100
+ spentTxHash: input.txHash || null,
101
+ spentOutputIndex: Number.isInteger(input.outputIndex) ? input.outputIndex : null,
98
102
  isCollateral: Boolean(input.isCollateral),
99
103
  isReference: Boolean(input.isReference),
100
104
  hasAddresses: hasAddress,
@@ -102,23 +106,17 @@ function mapTransactionInputs(txHash, txInputs) {
102
106
  };
103
107
  });
104
108
  }
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
- */
112
- function mapTransactionInputAssets(txHash, inputs) {
109
+ /** Provider transaction input assets to TransactionInputAssetRows. */
110
+ function mapTransactionInputAssets(txSeq, inputs) {
113
111
  return inputs.flatMap((input, idx) => {
114
- // Use array index as the input index (must match mapTransactionInputs)
112
+ // must match mapTransactionInputs
115
113
  const inputIndex = idx;
116
114
  if (!Array.isArray(input.amount))
117
115
  return [];
118
116
  return input.amount.map(a => {
119
117
  const { policyId, assetName } = parseAssetUnit(a.unit);
120
118
  return {
121
- input_tx_hash: txHash,
119
+ input_txSeq: txSeq,
122
120
  input_inputIndex: inputIndex,
123
121
  unit: a.unit,
124
122
  asset_quantity: a.quantity,
@@ -128,20 +126,37 @@ function mapTransactionInputAssets(txHash, inputs) {
128
126
  });
129
127
  });
130
128
  }
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
- */
138
- function mapTransactionOutputs(txHash, txOutputs) {
129
+ /** Normalized certificates to TransactionCertificateRows, one per (certIndex, kind). */
130
+ function mapTransactionCertificates(txHash, certificates) {
131
+ return certificates.map((c) => ({
132
+ tx_hash: txHash,
133
+ certIndex: c.certIndex,
134
+ kind: c.kind,
135
+ stakeAddress: c.stakeAddress || null,
136
+ poolId: c.poolId || null,
137
+ drepId: c.drepId || null,
138
+ deposit: c.deposit != null ? String(c.deposit) : null,
139
+ epoch: c.epoch ?? null,
140
+ }));
141
+ }
142
+ /** Normalized withdrawals to TransactionWithdrawalRows, one per reward account. */
143
+ function mapTransactionWithdrawals(txHash, withdrawals) {
144
+ return withdrawals
145
+ .filter((w) => !!w.stakeAddress)
146
+ .map((w) => ({
147
+ tx_hash: txHash,
148
+ stakeAddress: w.stakeAddress,
149
+ lovelace: String(w.amount ?? '0'),
150
+ }));
151
+ }
152
+ /** Provider transaction outputs to TransactionOutputRows. */
153
+ function mapTransactionOutputs(txSeq, txOutputs) {
139
154
  return txOutputs.map((output) => {
140
155
  const outputIndex = output.outputIndex;
141
156
  const hasAddresses = !!output.address?.length;
142
157
  const hasAssets = Array.isArray(output.amount) && output.amount.length > 0;
143
158
  return {
144
- tx_hash: txHash,
159
+ txSeq,
145
160
  outputIndex: outputIndex,
146
161
  address_address: output.address,
147
162
  utxo_dataHash: output.dataHash || null,
@@ -152,14 +167,8 @@ function mapTransactionOutputs(txHash, txOutputs) {
152
167
  };
153
168
  });
154
169
  }
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
- */
162
- function mapTransactionOutputAssets(txHash, outputs) {
170
+ /** Provider transaction output assets to TransactionOutputAssetRows. */
171
+ function mapTransactionOutputAssets(txSeq, outputs) {
163
172
  return outputs.flatMap((output) => {
164
173
  const outputIndex = output.outputIndex;
165
174
  if (!Array.isArray(output.amount))
@@ -167,7 +176,7 @@ function mapTransactionOutputAssets(txHash, outputs) {
167
176
  return output.amount.map(a => {
168
177
  const { policyId, assetName } = parseAssetUnit(a.unit);
169
178
  return {
170
- output_tx_hash: txHash,
179
+ output_txSeq: txSeq,
171
180
  output_outputIndex: outputIndex,
172
181
  unit: a.unit,
173
182
  asset_quantity: a.quantity,
@@ -177,13 +186,7 @@ function mapTransactionOutputAssets(txHash, outputs) {
177
186
  });
178
187
  });
179
188
  }
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
- */
189
+ /** Provider address to a temporal AddressRow valid for `maxAge` ms. */
187
190
  function mapAddress(address, addressData, maxAge) {
188
191
  const now = Date.now();
189
192
  const nowIso = new Date(now).toISOString();
@@ -194,7 +197,7 @@ function mapAddress(address, addressData, maxAge) {
194
197
  const utxoCount = Array.isArray(addressData.utxos) ? addressData.utxos.length : 0;
195
198
  const hasUtxos = utxoCount > 0;
196
199
  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
200
+ // set to true by indexAddress() once transactions are indexed
198
201
  const hasTransactions = false;
199
202
  return {
200
203
  address,
@@ -210,19 +213,9 @@ function mapAddress(address, addressData, maxAge) {
210
213
  hasTransactions: hasTransactions,
211
214
  };
212
215
  }
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.
216
+ /** Provider transactions to AddressTransactionRows with the address's net amounts; non-temporal. */
223
217
  function mapAddressTransactions(addr, addressTxsData) {
224
218
  return addressTxsData.map((tx) => {
225
- // Calculate net amounts for this address in this transaction
226
219
  const { netLovelace, netAssets } = calculateNetAmounts(addr, tx);
227
220
  return {
228
221
  address_address: addr,
@@ -234,17 +227,11 @@ function mapAddressTransactions(addr, addressTxsData) {
234
227
  };
235
228
  });
236
229
  }
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
- */
230
+ /** Net lovelace and asset changes of an address in a transaction (outputs minus inputs). */
243
231
  function calculateNetAmounts(addr, tx) {
244
232
  let inputLovelace = 0n;
245
233
  let outputLovelace = 0n;
246
234
  const assetBalances = new Map(); // unit -> net quantity
247
- // Process inputs belonging to this address (subtract)
248
235
  for (const input of tx.inputs ?? []) {
249
236
  if (input.address === addr) {
250
237
  for (const amount of input.amount ?? []) {
@@ -252,14 +239,12 @@ function calculateNetAmounts(addr, tx) {
252
239
  inputLovelace += BigInt(amount.quantity || '0');
253
240
  }
254
241
  else {
255
- // Native asset
256
242
  const current = assetBalances.get(amount.unit) || 0n;
257
243
  assetBalances.set(amount.unit, current - BigInt(amount.quantity || '0'));
258
244
  }
259
245
  }
260
246
  }
261
247
  }
262
- // Process outputs going to this address (add)
263
248
  for (const output of tx.outputs ?? []) {
264
249
  if (output.address === addr) {
265
250
  for (const amount of output.amount ?? []) {
@@ -267,19 +252,16 @@ function calculateNetAmounts(addr, tx) {
267
252
  outputLovelace += BigInt(amount.quantity || '0');
268
253
  }
269
254
  else {
270
- // Native asset
271
255
  const current = assetBalances.get(amount.unit) || 0n;
272
256
  assetBalances.set(amount.unit, current + BigInt(amount.quantity || '0'));
273
257
  }
274
258
  }
275
259
  }
276
260
  }
277
- // Convert asset map to array, filtering out zero balances
261
+ // zero balances are dropped
278
262
  const netAssets = [];
279
263
  for (const [unit, quantity] of assetBalances) {
280
264
  if (quantity !== 0n) {
281
- // Parse unit into policyId and assetName
282
- // Format: policyId (56 chars) + assetNameHex
283
265
  const policyId = unit.substring(0, 56);
284
266
  const assetNameHex = unit.substring(56);
285
267
  const assetName = hexToUtf8(assetNameHex);
@@ -297,14 +279,7 @@ function calculateNetAmounts(addr, tx) {
297
279
  netAssets
298
280
  };
299
281
  }
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
- */
282
+ /** Provider UTxOs to temporal AddressUTxORows. */
308
283
  function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
309
284
  return addressUtxosData.map((utxo) => {
310
285
  const amounts = Array.isArray(utxo.amount) ? utxo.amount : [];
@@ -317,10 +292,8 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
317
292
  blockHash: utxo.blockHash,
318
293
  utxodata_dataHash: utxo.datumHash,
319
294
  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.
295
+ // Hash column: Blockfrost/Ogmios give a 56-hex hash, Koios the full script CBOR, so only
296
+ // hash-length values are persisted
324
297
  utxodata_referenceScriptHash: utxo.scriptRef && utxo.scriptRef.length <= 64 ? utxo.scriptRef : null,
325
298
  lovelace: lovelace,
326
299
  validFrom: validFrom,
@@ -329,15 +302,7 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
329
302
  };
330
303
  });
331
304
  }
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
- */
305
+ /** Provider address amounts (without lovelace) to temporal AddressAssetRows. */
341
306
  function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
342
307
  return AssetAssets
343
308
  .filter((asset) => asset.unit !== 'lovelace')
@@ -354,14 +319,7 @@ function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
354
319
  };
355
320
  });
356
321
  }
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
- */
322
+ /** Native assets of provider UTxOs to temporal UTxOAssetRows. */
365
323
  function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
366
324
  const assets = [];
367
325
  addressUtxosData.forEach((utxo) => {
@@ -385,12 +343,7 @@ function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
385
343
  });
386
344
  return assets;
387
345
  }
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
- */
346
+ /** Provider network information to a temporal NetworkInfoRow. */
394
347
  function mapNetworkInfo(providerNetworkData, max_age, network) {
395
348
  const now = Date.now();
396
349
  const nowIso = new Date(now).toISOString();
@@ -409,23 +362,16 @@ function mapNetworkInfo(providerNetworkData, max_age, network) {
409
362
  activeStake: providerNetworkData.stake.active,
410
363
  };
411
364
  }
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
- */
365
+ /** Provider block to BlockRow. */
419
366
  function mapBlock(providerBlockData, epochData) {
420
367
  return {
421
368
  time: new Date(providerBlockData.time * 1000).toISOString(),
422
369
  height: providerBlockData.height,
423
370
  hash: providerBlockData.hash,
424
- // was `String(x ?? null)` → persisted the literal string "null" when absent
425
371
  slotLeader: providerBlockData.slotLeader ?? null,
426
372
  epochNumber: epochData?.epoch ?? providerBlockData.epoch,
427
373
  epoch: epochData,
428
- // absolute slot — the crawler's reorg cut axis (same axis as Transactions.slot)
374
+ // absolute slot: the crawler's reorg cut axis (same as Transactions.slot)
429
375
  slot: providerBlockData.slot ?? null,
430
376
  epochSlot: providerBlockData.epochSlot,
431
377
  size: providerBlockData.size,
@@ -433,12 +379,7 @@ function mapBlock(providerBlockData, epochData) {
433
379
  fees: providerBlockData.fees ?? '0',
434
380
  };
435
381
  }
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
- */
382
+ /** Provider epoch to EpochRow. */
442
383
  function mapEpoch(providerEpochData) {
443
384
  return {
444
385
  epoch: providerEpochData.epoch,
@@ -453,44 +394,86 @@ function mapEpoch(providerEpochData) {
453
394
  activeStake: providerEpochData.active_stake,
454
395
  };
455
396
  }
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
- */
397
+ /** Provider metadata labels to TransactionMetadataRows; non-uint64 labels are skipped. */
462
398
  function mapTransactionMetadata(providerLabels) {
463
399
  const rows = [];
464
400
  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)`);
401
+ const id = metadataIdFor(lbl.label);
402
+ if (id === null) {
403
+ // a NaN key would fail the whole bulk write on PostgreSQL
404
+ logger.warn(`Metadata label ${JSON.stringify(lbl.label)} of tx ${lbl.txHash} is not a uint64 — row skipped`);
405
+ continue;
470
406
  }
471
407
  rows.push({
472
- id: numericId,
408
+ // exact int64 key (see metadataIdFor); `label` keeps the original string
409
+ id: id,
473
410
  tx_hash: lbl.txHash,
474
411
  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.
412
+ // Ogmios exposes numeric metadata as bigint; safeJSON writes exact number tokens
478
413
  payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
479
414
  });
480
415
  }
481
416
  return rows;
482
417
  }
483
418
  /**
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
419
+ * uint64 metadata label to the int64 `TransactionMetadata.id` key: labels >= 2^63 wrap via two's complement,
420
+ * values beyond 2^53 are passed as a decimal string (CAP accepts strings for Integer64).
421
+ * @returns the key, or null when the label is not a non-negative integer
488
422
  */
423
+ function metadataIdFor(label) {
424
+ let big;
425
+ if (typeof label === 'number') {
426
+ if (!Number.isFinite(label))
427
+ return null;
428
+ big = BigInt(Math.trunc(label));
429
+ }
430
+ else {
431
+ const text = String(label).trim();
432
+ if (!/^\d+$/.test(text))
433
+ return null;
434
+ big = BigInt(text);
435
+ }
436
+ const wrapped = BigInt.asIntN(64, big);
437
+ const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
438
+ return safe ? Number(wrapped) : wrapped.toString();
439
+ }
440
+ /** Pool observation at an epoch boundary to a non-temporal PoolEpochSnapshotRow dated by (epoch, snapshotSlot). */
441
+ function mapPoolSnapshot(providerPoolData, epoch, at) {
442
+ return {
443
+ poolId: providerPoolData.poolId,
444
+ epoch,
445
+ snapshotSlot: at.slot,
446
+ snapshotTime: at.time,
447
+ blocksMinted: providerPoolData.blocksMinted,
448
+ blocksEpoch: providerPoolData.blocksEpoch,
449
+ liveStake: providerPoolData.liveStake,
450
+ liveSize: Number(providerPoolData.liveSize),
451
+ liveSaturation: Number(providerPoolData.liveSaturation),
452
+ liveDelegators: providerPoolData.liveDelegators,
453
+ activeStake: providerPoolData.activeStake,
454
+ activeSize: Number(providerPoolData.activeSize),
455
+ pledge: providerPoolData.pledge,
456
+ margin: Number(providerPoolData.margin),
457
+ fixedCost: providerPoolData.fixedCost,
458
+ };
459
+ }
460
+ /** DRep observation at an epoch boundary to a non-temporal DrepEpochSnapshotRow. */
461
+ function mapDrepSnapshot(providerDrepData, epoch, at) {
462
+ return {
463
+ drepId: providerDrepData.drepId,
464
+ epoch,
465
+ snapshotSlot: at.slot,
466
+ snapshotTime: at.time,
467
+ amount: providerDrepData.amount,
468
+ hasScript: providerDrepData.hasScript,
469
+ lastActiveEpoch: providerDrepData.lastActiveEpoch,
470
+ retired: providerDrepData.retired,
471
+ expired: providerDrepData.expired,
472
+ };
473
+ }
474
+ /** Provider pool to a temporal PoolRow valid for `max_age` ms. */
489
475
  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.
476
+ // one clock read, so validTo - validFrom is exactly max_age
494
477
  const now = Date.now();
495
478
  const validFrom = new Date(now).toISOString();
496
479
  const validTo = new Date(now + max_age).toISOString();
@@ -513,17 +496,9 @@ function mapPool(providerPoolData, max_age) {
513
496
  validTo,
514
497
  };
515
498
  }
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
- */
499
+ /** Canonical asset info to a temporal AssetRow valid for `max_age` ms; on-chain metadata is JSON-stringified. */
525
500
  function mapAsset(providerAssetInfo, max_age) {
526
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
501
+ // one clock read (see mapPool)
527
502
  const now = Date.now();
528
503
  const validFrom = new Date(now).toISOString();
529
504
  const validTo = new Date(now + max_age).toISOString();
@@ -551,11 +526,45 @@ function mapAsset(providerAssetInfo, max_age) {
551
526
  };
552
527
  }
553
528
  /**
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
529
+ * Fixed validity stamp for a crawler-written bare `Assets` row: epoch zero, so the row is born expired
530
+ * (hidden by CAP's temporal filter) and its `(validFrom, unit)` key never collides with a mapAsset() slice.
558
531
  */
532
+ exports.BARE_ASSET_STAMP = '1970-01-01T00:00:00.000Z';
533
+ /**
534
+ * Bare AssetRow from the unit alone (policyId, assetNameHex, decoded name, CIP-14 fingerprint), no provider call.
535
+ * Stamped `validTo === validFrom` with the fixed sentinel: hidden from OData reads, so the first keyed read
536
+ * still misses and the lazy path enriches it; one idempotent row per unit inside the crawler's block tx.
537
+ * @returns the row, or null when the unit is not a native asset unit
538
+ */
539
+ function mapBareAsset(unit) {
540
+ // same unit definition isAssetUnit() enforces on the API
541
+ if (!const_1.ASSET_UNIT_REGEX.test(unit))
542
+ return null;
543
+ const policyId = unit.slice(0, 56);
544
+ const assetNameHex = unit.slice(56);
545
+ return {
546
+ unit,
547
+ policyId,
548
+ assetNameHex,
549
+ // hex fallback for non-text and NUL-bearing names
550
+ assetName: assetNameHex.length > 0 ? decodeAssetName(assetNameHex) : '',
551
+ fingerprint: computeCip14Fingerprint(policyId, assetNameHex),
552
+ totalSupply: null,
553
+ mintOrBurnCount: null,
554
+ initialMintTxHash: null,
555
+ initialMintTime: null,
556
+ onchainMetadata: null,
557
+ registryName: null,
558
+ registryTicker: null,
559
+ registryDecimals: null,
560
+ registryDescription: null,
561
+ registryUrl: null,
562
+ registryLogo: null,
563
+ validFrom: exports.BARE_ASSET_STAMP,
564
+ validTo: exports.BARE_ASSET_STAMP,
565
+ };
566
+ }
567
+ /** Asset history events to non-temporal AssetHistoryRows (immutable, keyed on unit + txHash). */
559
568
  function mapAssetHistory(entries) {
560
569
  return entries.map((e) => ({
561
570
  unit: e.unit,
@@ -566,16 +575,9 @@ function mapAssetHistory(entries) {
566
575
  blockHeight: e.blockHeight,
567
576
  }));
568
577
  }
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
- */
578
+ /** Provider DRep to a temporal DrepRow valid for `max_age` ms. */
575
579
  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).
580
+ // one clock read (see mapPool)
579
581
  const now = Date.now();
580
582
  const validFrom = new Date(now).toISOString();
581
583
  const validTo = new Date(now + max_age).toISOString();
@@ -591,14 +593,9 @@ function mapDrep(providerDrepData, max_age) {
591
593
  validTo,
592
594
  };
593
595
  }
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
- */
596
+ /** Provider account to a temporal AccountRow valid for `max_age` ms. */
600
597
  function mapAccount(providerAccountData, max_age) {
601
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
598
+ // one clock read (see mapPool)
602
599
  const now = Date.now();
603
600
  const validFrom = new Date(now).toISOString();
604
601
  const validTo = new Date(now + max_age).toISOString();
@@ -614,35 +611,24 @@ function mapAccount(providerAccountData, max_age) {
614
611
  reservesSum: providerAccountData.reservesSum,
615
612
  treasurySum: providerAccountData.treasurySum,
616
613
  withdrawableAmount: providerAccountData.withdrawableAmount,
614
+ poolId_poolId: providerAccountData.poolId ?? null,
615
+ drepId_drepId: providerAccountData.drepId ?? null,
617
616
  hasAddresses: providerAccountData.addresses.length > 0,
618
617
  };
619
618
  }
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
- */
619
+ /** Rejects the OData request for a BackendError; unknown errors are logged and answered as a sanitized 500. */
627
620
  function mapError(req, err, ctx) {
628
621
  if (err instanceof errors_1.BackendError) {
629
622
  return req.reject(err.statusCode, fmt(err.code, ctx, err.message), err.target);
630
623
  }
631
- // Handle non-BackendError (plain Error, string, etc.)
632
- // Log full error server-side, but return sanitized message to client
633
624
  const internalMsg = err instanceof Error ? err.message : String(err);
634
625
  logger.error({ error: internalMsg }, `Unexpected error in ${ctx}`);
635
626
  return req.reject(500, fmt('INTERNAL_ERROR', ctx, 'An internal error occurred'));
636
627
  }
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
- */
628
+ /** Build result to a temporal TransactionBuildRow with a fresh build id. */
643
629
  function mapBuildResult(txbuildResult, max_age) {
644
630
  const buildId = cds_1.default.utils.uuid();
645
- // Read the clock once so validTo - validFrom is exactly max_age (see mapPool).
631
+ // one clock read (see mapPool)
646
632
  const nowMs = Date.now();
647
633
  const now = Math.floor(nowMs / 1000);
648
634
  const validFrom = new Date(nowMs).toISOString();
@@ -660,25 +646,19 @@ function mapBuildResult(txbuildResult, max_age) {
660
646
  unsignedTxCbor: txbuildResult.unsignedTxCbor,
661
647
  txBodyHash: txbuildResult.txBodyHash,
662
648
  fee: txbuildResult.feeLovelace,
663
- size: txbuildResult.sizeBytes, // size in bytes
649
+ size: txbuildResult.sizeBytes, // bytes
664
650
  createdAt: now, // epoch seconds
665
651
  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
652
+ hasInputs: hasInputs,
653
+ hasOutputs: hasOutputs,
654
+ wasSubmitted: false,
669
655
  scriptHash: txbuildResult.scriptHash ?? null,
670
656
  mintScriptHash: txbuildResult.mintScriptHash ?? null,
671
657
  forcedInputsUsed: txbuildResult.forcedInputsUsed ?? 0,
672
658
  referenceInputsUsed: txbuildResult.referenceInputsUsed ?? 0,
673
659
  };
674
660
  }
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
- */
661
+ /** Build result inputs to TransactionBuildInputRows. */
682
662
  function mapBuildInputs(buildId, inputs) {
683
663
  return inputs.map((input, idx) => ({
684
664
  build_id: buildId,
@@ -690,14 +670,7 @@ function mapBuildInputs(buildId, inputs) {
690
670
  hasAssets: false, // simple ADA transfers don't have assets
691
671
  }));
692
672
  }
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
- */
673
+ /** Build result outputs to TransactionBuildOutputRows; `changeAddress` marks the change output. */
701
674
  function mapBuildOutputs(buildId, outputs, changeAddress) {
702
675
  return outputs.map((output, idx) => ({
703
676
  build_id: buildId,
@@ -708,12 +681,7 @@ function mapBuildOutputs(buildId, outputs, changeAddress) {
708
681
  hasAssets: false, // simple ADA transfers don't have assets
709
682
  }));
710
683
  }
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
- */
684
+ /** Provider protocol parameters to ProtocolParameterRow. */
717
685
  function mapProtocolParameters(providerParams) {
718
686
  return {
719
687
  network: providerParams.network,
@@ -752,13 +720,7 @@ function mapProtocolParameters(providerParams) {
752
720
  source: providerParams.source,
753
721
  };
754
722
  }
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
- */
723
+ /** Signed tx CBOR and hash to a TransactionSubmissionRow stamped now (epoch seconds). */
762
724
  function mapTransactionSubmission(signedTxCbor, txHash) {
763
725
  const now = Math.floor(Date.now() / 1000);
764
726
  return {
@@ -767,26 +729,14 @@ function mapTransactionSubmission(signedTxCbor, txHash) {
767
729
  submittedAt: now,
768
730
  };
769
731
  }
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
- */
732
+ /** Address to signing-request association row. */
777
733
  function mapAddressSigningRequest(addr, signingRequestId) {
778
734
  return {
779
735
  address_address: addr,
780
736
  signingRequest_id: signingRequestId,
781
737
  };
782
738
  }
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
- */
739
+ /** Address to transaction-build association row. */
790
740
  function mapAddressTransactionBuild(addr, buildId) {
791
741
  return {
792
742
  address_address: addr,
@@ -797,19 +747,8 @@ function mapAddressTransactionBuild(addr, buildId) {
797
747
  // Helper Functions
798
748
  //-----------------------------------------------------------------------
799
749
  /**
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
750
+ * Cost models to number arrays in canonical Plutus parameter order. V3 goes through toCostModelArrV3
751
+ * (canonical keys, padded to 297); for V1/V2 alphabetical key order is the canonical order.
813
752
  */
814
753
  function normalizeCostModels(raw) {
815
754
  const result = {};
@@ -817,12 +756,10 @@ function normalizeCostModels(raw) {
817
756
  const isV3 = key === 'PlutusV3' || key === 'plutus:v3';
818
757
  if (Array.isArray(value)) {
819
758
  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.
759
+ // already canonical; toCostModelArrV3 pads short arrays to 297 with defaults
822
760
  result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(value)).map(Number);
823
761
  }
824
762
  else {
825
- // V1/V2: pass through (already in canonical order)
826
763
  result[key] = value;
827
764
  }
828
765
  }
@@ -832,7 +769,6 @@ function normalizeCostModels(raw) {
832
769
  result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(obj)).map(Number);
833
770
  }
834
771
  else {
835
- // V1/V2: alphabetical sort IS correct for those versions
836
772
  result[key] = Object.keys(obj).sort()
837
773
  .map(k => obj[k]);
838
774
  }
@@ -840,25 +776,29 @@ function normalizeCostModels(raw) {
840
776
  }
841
777
  return result;
842
778
  }
779
+ /** Hex to UTF-8 display string, hex fallback (see decodeAssetName). */
780
+ function hexToUtf8(hex) {
781
+ return decodeAssetName(hex);
782
+ }
783
+ // ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the round trip
784
+ const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
843
785
  /**
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
786
+ * Asset name (hex bytes) to its display string; the hex is returned unchanged for invalid UTF-8 or
787
+ * names containing U+0000 (PostgreSQL rejects NUL in `text`). `assetNameHex` always keeps the exact bytes.
850
788
  */
851
- function hexToUtf8(hex) {
789
+ function decodeAssetName(hex) {
852
790
  if (!hex)
853
791
  return hex;
854
- return Buffer.from(hex, 'hex').toString('utf8');
792
+ let text;
793
+ try {
794
+ text = strictUtf8.decode(Buffer.from(hex, 'hex'));
795
+ }
796
+ catch {
797
+ return hex;
798
+ }
799
+ return text.includes('\u0000') ? hex : text;
855
800
  }
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
- */
801
+ /** Split an asset unit into policyId and decoded assetName; `lovelace` and malformed units get a null policyId. */
862
802
  function parseAssetUnit(unit) {
863
803
  if (unit === 'lovelace') {
864
804
  return { policyId: null, assetName: 'lovelace' };
@@ -871,13 +811,7 @@ function parseAssetUnit(unit) {
871
811
  const assetName = assetNameHex.length > 0 ? hexToUtf8(assetNameHex) : '';
872
812
  return { policyId, assetName };
873
813
  }
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
- */
814
+ /** CIP-14 fingerprint: bech32("asset", blake2b_160(policyId_bytes + assetName_bytes)). */
881
815
  function computeCip14Fingerprint(policyIdHex, assetNameHex) {
882
816
  const input = Buffer.from(policyIdHex + assetNameHex, 'hex');
883
817
  const out = Buffer.alloc(20);
@@ -885,11 +819,7 @@ function computeCip14Fingerprint(policyIdHex, assetNameHex) {
885
819
  const words = bech32_1.bech32.toWords(out);
886
820
  return bech32_1.bech32.encode('asset', words);
887
821
  }
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
- */
822
+ /** Enterprise script address: header 0x71 (mainnet) / 0x70 (testnet) + 28-byte script hash, bech32. */
893
823
  function scriptHashToEnterpriseAddress(scriptHashHex, network) {
894
824
  const headerByte = network === 'mainnet' ? 0x71 : 0x70;
895
825
  const payload = Buffer.alloc(29);
@@ -899,13 +829,71 @@ function scriptHashToEnterpriseAddress(scriptHashHex, network) {
899
829
  const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
900
830
  return bech32_1.bech32.encode(hrp, words, 120);
901
831
  }
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
- */
832
+ /** Stake credential to bech32 reward account; header nibbles 0xe key / 0xf script, network 1 mainnet / 0 testnets. */
833
+ function credentialToStakeAddress(credentialHex, isScript, network) {
834
+ const header = (isScript ? 0xf0 : 0xe0) | (network === 'mainnet' ? 0x01 : 0x00);
835
+ const payload = Buffer.alloc(29);
836
+ payload[0] = header;
837
+ Buffer.from(credentialHex, 'hex').copy(payload, 1);
838
+ const hrp = network === 'mainnet' ? 'stake' : 'stake_test';
839
+ return bech32_1.bech32.encode(hrp, bech32_1.bech32.toWords(payload), 120);
840
+ }
841
+ /**
842
+ * Decode the CIP-19 Shelley address header: type, script flag and, for base addresses, the embedded
843
+ * stake credential as a reward account. Byron (base58) and unparseable input yield `byron` / `unknown`.
844
+ */
845
+ function decodeShelleyAddress(address) {
846
+ const none = { type: 'unknown', isScript: false, stakeAddress: null, networkId: null };
847
+ if (typeof address !== 'string' || !address.length)
848
+ return none;
849
+ let bytes;
850
+ try {
851
+ const decoded = bech32_1.bech32.decode(address, 120);
852
+ if (decoded.prefix !== 'addr' && decoded.prefix !== 'addr_test' && decoded.prefix !== 'stake' && decoded.prefix !== 'stake_test')
853
+ return none;
854
+ bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
855
+ }
856
+ catch {
857
+ // Byron addresses are base58 and start with Ae2 / DdzFF (mainnet) or 2cWKM… (testnets)
858
+ return /^(Ae2|DdzFF|2cWKM|37btj|KjgoiX)/.test(address) ? { ...none, type: 'byron' } : none;
859
+ }
860
+ if (!bytes.length)
861
+ return none;
862
+ const header = bytes[0];
863
+ const type = header >> 4;
864
+ const networkId = header & 0x0f;
865
+ const net = networkId === 1 ? 'mainnet' : 'preview';
866
+ switch (type) {
867
+ case 0:
868
+ case 1:
869
+ case 2:
870
+ case 3: {
871
+ const stakeAddress = bytes.length >= 57
872
+ ? credentialToStakeAddress(bytes.subarray(29, 57).toString('hex'), type >= 2, net)
873
+ : null;
874
+ return { type: 'base', isScript: type === 1 || type === 3, stakeAddress, networkId };
875
+ }
876
+ case 4:
877
+ case 5:
878
+ return { type: 'pointer', isScript: type === 5, stakeAddress: null, networkId };
879
+ case 6:
880
+ case 7:
881
+ return { type: 'enterprise', isScript: type === 7, stakeAddress: null, networkId };
882
+ case 14:
883
+ case 15:
884
+ return { type: 'reward', isScript: type === 15, stakeAddress: address, networkId };
885
+ default:
886
+ return { ...none, networkId };
887
+ }
888
+ }
889
+ /** DRep credential to CIP-129 DRep ID (29 bytes): header 0x22 key hash / 0x23 script hash. */
890
+ function credentialToDrepId(credentialHex, isScript) {
891
+ const payload = Buffer.alloc(29);
892
+ payload[0] = isScript ? 0x23 : 0x22;
893
+ Buffer.from(credentialHex, 'hex').copy(payload, 1);
894
+ return bech32_1.bech32.encode('drep', bech32_1.bech32.toWords(payload), 120);
895
+ }
896
+ /** `[code] ctx: msg` */
909
897
  function fmt(code, ctx, msg) {
910
898
  return `[${code}] ${ctx}: ${msg}`;
911
899
  }