@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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