@odatano/core 2.0.0-rc.3 → 2.0.0-rc.31

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