@odatano/core 2.0.0-rc.50 → 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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -45,6 +45,7 @@ exports.mapAddressSigningRequest = mapAddressSigningRequest;
45
45
  exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
46
46
  exports.normalizeCostModels = normalizeCostModels;
47
47
  exports.decodeAssetName = decodeAssetName;
48
+ exports.assetSlice = assetSlice;
48
49
  exports.computeCip14Fingerprint = computeCip14Fingerprint;
49
50
  exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
50
51
  exports.credentialToStakeAddress = credentialToStakeAddress;
@@ -126,17 +127,12 @@ function mapTransactionInputAssets(txSeq, inputs, byReference = false) {
126
127
  const inputIndex = idx;
127
128
  if (!Array.isArray(input.amount) || (byReference && input.spentTxSeq != null))
128
129
  return [];
129
- return input.amount.map(a => {
130
- const { policyId, assetName } = parseAssetUnit(a.unit);
131
- return {
132
- input_txSeq: txSeq,
133
- input_inputIndex: inputIndex,
134
- unit: a.unit,
135
- asset_quantity: a.quantity,
136
- asset_policyId: policyId,
137
- asset_assetName: assetName,
138
- };
139
- });
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
+ }));
140
136
  });
141
137
  }
142
138
  /** Normalized certificates to TransactionCertificateRows, one per (certIndex, kind). */
@@ -235,17 +231,12 @@ function mapTransactionOutputAssets(txSeq, outputs) {
235
231
  const outputIndex = output.outputIndex;
236
232
  if (!Array.isArray(output.amount))
237
233
  return [];
238
- return output.amount.map(a => {
239
- const { policyId, assetName } = parseAssetUnit(a.unit);
240
- return {
241
- output_txSeq: txSeq,
242
- output_outputIndex: outputIndex,
243
- unit: a.unit,
244
- asset_quantity: a.quantity,
245
- asset_policyId: policyId,
246
- asset_assetName: assetName,
247
- };
248
- });
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
+ }));
249
240
  });
250
241
  }
251
242
  /** Provider address to a temporal AddressRow valid for `maxAge` ms. */
@@ -295,6 +286,9 @@ function calculateNetAmounts(addr, tx) {
295
286
  let outputLovelace = 0n;
296
287
  const assetBalances = new Map(); // unit -> net quantity
297
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;
298
292
  if (input.address === addr) {
299
293
  for (const amount of input.amount ?? []) {
300
294
  if (amount.unit === 'lovelace') {
@@ -324,15 +318,13 @@ function calculateNetAmounts(addr, tx) {
324
318
  const netAssets = [];
325
319
  for (const [unit, quantity] of assetBalances) {
326
320
  if (quantity !== 0n) {
327
- const policyId = unit.substring(0, 56);
328
- const assetNameHex = unit.substring(56);
329
- const assetName = hexToUtf8(assetNameHex);
321
+ const slice = assetSlice(unit, quantity.toString());
330
322
  netAssets.push({
331
323
  unit,
332
- policyId,
333
- assetName,
334
- assetNameHex,
335
- quantity: quantity.toString()
324
+ policyId: slice.asset_policyId ?? '',
325
+ assetName: slice.asset_assetName,
326
+ assetNameHex: slice.asset_assetNameHex ?? '',
327
+ quantity: slice.asset_quantity,
336
328
  });
337
329
  }
338
330
  }
@@ -371,18 +363,13 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
371
363
  function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
372
364
  return AssetAssets
373
365
  .filter((asset) => asset.unit !== 'lovelace')
374
- .map((asset) => {
375
- const { policyId, assetName } = parseAssetUnit(asset.unit);
376
- return {
377
- address_address: addr,
378
- unit: asset.unit,
379
- validFrom: validFrom,
380
- validTo: validTo,
381
- asset_quantity: asset.quantity,
382
- asset_policyId: policyId,
383
- asset_assetName: assetName,
384
- };
385
- });
366
+ .map((asset) => ({
367
+ address_address: addr,
368
+ unit: asset.unit,
369
+ validFrom: validFrom,
370
+ validTo: validTo,
371
+ ...assetSlice(asset.unit, asset.quantity),
372
+ }));
386
373
  }
387
374
  /** Native assets of provider UTxOs to temporal UTxOAssetRows. */
388
375
  function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
@@ -392,7 +379,6 @@ function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
392
379
  for (const asset of amounts) {
393
380
  if (!asset || !asset.unit || asset.unit === 'lovelace')
394
381
  continue;
395
- const { policyId, assetName } = parseAssetUnit(asset.unit);
396
382
  assets.push({
397
383
  utxo_address_address: utxo.address,
398
384
  utxo_hash: utxo.txHash,
@@ -400,9 +386,7 @@ function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
400
386
  unit: asset.unit,
401
387
  validFrom: validFrom,
402
388
  validTo: validTo,
403
- asset_quantity: asset.quantity,
404
- asset_policyId: policyId,
405
- asset_assetName: assetName,
389
+ ...assetSlice(asset.unit, asset.quantity),
406
390
  });
407
391
  }
408
392
  });
@@ -442,6 +426,8 @@ function mapBlock(providerBlockData, epochData) {
442
426
  size: providerBlockData.size,
443
427
  txCount: providerBlockData.txCount,
444
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 } : {}),
445
431
  };
446
432
  }
447
433
  /** Provider epoch to EpochRow. */
@@ -482,8 +468,9 @@ function mapTransactionMetadata(providerLabels, txSeq) {
482
468
  }
483
469
  return rows;
484
470
  }
471
+ const MAX_UINT64 = 2n ** 64n - 1n;
485
472
  // Maps a uint64 metadata label to the int64 id key. Labels >= 2^63 wrap by two's complement.
486
- // Values beyond 2^53 are returned as a decimal string. Null when the label is no non-negative integer.
473
+ // Values beyond 2^53 are returned as a decimal string. Null when the label is no uint64.
487
474
  function metadataIdFor(label) {
488
475
  let big;
489
476
  if (typeof label === 'number') {
@@ -497,6 +484,8 @@ function metadataIdFor(label) {
497
484
  return null;
498
485
  big = BigInt(text);
499
486
  }
487
+ if (big < 0n || big > MAX_UINT64)
488
+ return null;
500
489
  const wrapped = BigInt.asIntN(64, big);
501
490
  const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
502
491
  return safe ? Number(wrapped) : wrapped.toString();
@@ -514,10 +503,10 @@ function mapPoolSnapshot(providerPoolData, epoch, at, origin = { source: 'koios'
514
503
  blocksEpoch: providerPoolData.blocksEpoch,
515
504
  liveStake: providerPoolData.liveStake,
516
505
  liveSize: providerPoolData.liveSize == null ? null : Number(providerPoolData.liveSize),
517
- liveSaturation: Number(providerPoolData.liveSaturation),
506
+ liveSaturation: providerPoolData.liveSaturation == null ? null : Number(providerPoolData.liveSaturation),
518
507
  liveDelegators: providerPoolData.liveDelegators,
519
508
  activeStake: providerPoolData.activeStake,
520
- activeSize: Number(providerPoolData.activeSize),
509
+ activeSize: providerPoolData.activeSize == null ? null : Number(providerPoolData.activeSize),
521
510
  pledge: providerPoolData.pledge,
522
511
  margin: Number(providerPoolData.margin),
523
512
  fixedCost: providerPoolData.fixedCost,
@@ -619,8 +608,8 @@ function mapBareAsset(unit) {
619
608
  unit,
620
609
  policyId,
621
610
  assetNameHex,
622
- // hex fallback for non-text and NUL-bearing names
623
- assetName: assetNameHex.length > 0 ? decodeAssetName(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,
624
613
  fingerprint: computeCip14Fingerprint(policyId, assetNameHex),
625
614
  totalSupply: null,
626
615
  mintOrBurnCount: null,
@@ -716,7 +705,7 @@ function mapBuildResult(txbuildResult, max_age) {
716
705
  builderEngine: txbuildResult.builderEngine,
717
706
  network: txbuildResult.network,
718
707
  senderAddress: txbuildResult.senderAddress,
719
- changeAddress: txbuildResult.changeOutput?.address ?? txbuildResult.senderAddress,
708
+ changeAddress: txbuildResult.changeAddress ?? txbuildResult.senderAddress,
720
709
  unsignedTxCbor: txbuildResult.unsignedTxCbor,
721
710
  txBodyHash: txbuildResult.txBodyHash,
722
711
  fee: txbuildResult.feeLovelace,
@@ -849,10 +838,6 @@ function normalizeCostModels(raw) {
849
838
  }
850
839
  return result;
851
840
  }
852
- /** Hex to UTF-8 display string, hex fallback (see decodeAssetName). */
853
- function hexToUtf8(hex) {
854
- return decodeAssetName(hex);
855
- }
856
841
  // ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the round trip
857
842
  const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
858
843
  // Display string for a hex asset name. Invalid UTF-8 or names with U+0000 return the hex unchanged,
@@ -869,18 +854,23 @@ function decodeAssetName(hex) {
869
854
  }
870
855
  return text.includes('\u0000') ? hex : text;
871
856
  }
872
- /** Split an asset unit into policyId and decoded assetName; `lovelace` and malformed units get a null policyId. */
873
- function parseAssetUnit(unit) {
874
- if (unit === 'lovelace') {
875
- return { policyId: null, assetName: 'lovelace' };
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 };
876
864
  }
877
- if (unit.length < 56 || !/^[a-f0-9]+$/i.test(unit)) {
878
- return { policyId: null, assetName: unit };
879
- }
880
- const policyId = unit.slice(0, 56);
881
- const assetNameHex = unit.slice(56);
882
- const assetName = assetNameHex.length > 0 ? hexToUtf8(assetNameHex) : '';
883
- return { policyId, assetName };
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
+ };
884
874
  }
885
875
  /** CIP-14 fingerprint: bech32("asset", blake2b_160(policyId_bytes + assetName_bytes)). */
886
876
  function computeCip14Fingerprint(policyIdHex, assetNameHex) {
@@ -917,7 +907,7 @@ function decodeShelleyAddress(address) {
917
907
  return none;
918
908
  let bytes;
919
909
  try {
920
- const decoded = bech32_1.bech32.decode(address, 120);
910
+ const decoded = bech32_1.bech32.decode(address, const_1.BECH32_MAX_LENGTH);
921
911
  if (decoded.prefix !== 'addr' && decoded.prefix !== 'addr_test' && decoded.prefix !== 'stake' && decoded.prefix !== 'stake_test')
922
912
  return none;
923
913
  bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
@@ -0,0 +1,17 @@
1
+ import type { Request } from '@sap/cds';
2
+ /** The parent of a navigation read such as `Transactions('h')/inputs`: its entity, its keys, the navigation. */
3
+ export interface NavigationRead {
4
+ parent: string;
5
+ keys: Record<string, unknown>;
6
+ nav: string;
7
+ /** Keys of the navigation step, as in `Accounts('s')/Address('a')`; null for a plain collection. */
8
+ navKeys: Record<string, unknown> | null;
9
+ /** Segments of the path: 2 for `Parent(k)/nav`, more when it goes further. */
10
+ depth: number;
11
+ /** Name of every segment after the parent; `steps[0]` is `nav`. */
12
+ steps: string[];
13
+ }
14
+ /** The parent of `req` when it reads through a navigation, else null. */
15
+ export declare function navigationOf(req: Pick<Request, 'query'>): NavigationRead | null;
16
+ export declare function readKey(req: Pick<Request, 'query' | 'data'>, field: string): unknown;
17
+ //# sourceMappingURL=navigation.d.ts.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.navigationOf = navigationOf;
4
+ exports.readKey = readKey;
5
+ const nameOf = (segment) => typeof segment === 'string' ? segment : typeof segment?.id === 'string' ? segment.id : null;
6
+ const refOf = (req) => {
7
+ const ref = req.query?.SELECT?.from?.ref;
8
+ return Array.isArray(ref) ? ref : undefined;
9
+ };
10
+ /** The keys of a key segment, `ref = val` joined by `and`; null for any other predicate. */
11
+ function segmentKeys(segment) {
12
+ if (typeof segment !== 'object' || !Array.isArray(segment.where))
13
+ return null;
14
+ const keys = {};
15
+ const where = segment.where;
16
+ for (let i = 0; i < where.length; i += 4) {
17
+ const left = where[i];
18
+ const right = where[i + 2];
19
+ if (where[i + 1] !== '=' || !left?.ref || left.ref.length !== 1 || !right || !('val' in right))
20
+ return null;
21
+ if (i + 3 < where.length && where[i + 3] !== 'and')
22
+ return null;
23
+ keys[String(left.ref[0])] = right.val;
24
+ }
25
+ return keys;
26
+ }
27
+ /** The parent of `req` when it reads through a navigation, else null. */
28
+ function navigationOf(req) {
29
+ const ref = refOf(req);
30
+ if (!ref || ref.length < 2)
31
+ return null;
32
+ const head = ref[0];
33
+ const step = ref[1];
34
+ if (typeof head !== 'object' || typeof head.id !== 'string')
35
+ return null;
36
+ const nav = nameOf(step);
37
+ const keys = segmentKeys(head);
38
+ if (!nav || !keys)
39
+ return null;
40
+ const steps = ref.slice(1).map((s) => nameOf(s) ?? '');
41
+ return { parent: head.id.slice(head.id.lastIndexOf('.') + 1), keys, nav, navKeys: typeof step === 'string' ? null : segmentKeys(step), depth: ref.length, steps };
42
+ }
43
+ // The key `field` of a keyed read. The OData adapter puts it into req.data; a query built with
44
+ // cds.ql in the same process carries it only in its key segment.
45
+ function readKey(req, field) {
46
+ const fromData = req.data?.[field];
47
+ if (fromData !== undefined)
48
+ return fromData;
49
+ const ref = refOf(req);
50
+ return ref?.length === 1 ? segmentKeys(ref[0])?.[field] : undefined;
51
+ }
52
+ //# sourceMappingURL=navigation.js.map
@@ -1,6 +1,5 @@
1
1
  import type { Network } from '../blockchain/cardano-client';
2
2
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
3
3
  export declare function setActiveNetwork(n: Network | null): void;
4
- /** The active network, or `null` if the app context has not been initialized. */
5
4
  export declare function getActiveNetwork(): Network | null;
6
5
  //# sourceMappingURL=network-context.d.ts.map
@@ -2,15 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.setActiveNetwork = setActiveNetwork;
4
4
  exports.getActiveNetwork = getActiveNetwork;
5
+ const config_1 = require("../config");
5
6
  // Holds the active network so validators can read it without importing server.ts.
6
- // Null before bootstrap.
7
7
  let active = null;
8
+ const NETWORKS = ['mainnet', 'preview', 'preprod'];
8
9
  /** Record the active network. Pass `null` to clear (shutdown/reset). */
9
10
  function setActiveNetwork(n) {
10
11
  active = n;
11
12
  }
12
- /** The active network, or `null` if the app context has not been initialized. */
13
+ // The network of the running app context, else the configured one. Before the context exists a
14
+ // request is still checked against its network; the missing context then answers 503 by itself.
13
15
  function getActiveNetwork() {
14
- return active;
16
+ if (active)
17
+ return active;
18
+ const configured = (0, config_1.configuredNetworkName)();
19
+ return NETWORKS.includes(configured) ? configured : null;
15
20
  }
16
21
  //# sourceMappingURL=network-context.js.map
@@ -9,6 +9,7 @@ exports.installPostgresInlineJson = installPostgresInlineJson;
9
9
  // streams them through a temp table, which costs three round trips per write.
10
10
  // Streams a caller passes in keep the driver's path.
11
11
  const cds_1 = __importDefault(require("@sap/cds"));
12
+ const db_kind_1 = require("./db-kind");
12
13
  const stream_1 = require("stream");
13
14
  const logger = cds_1.default.log('PgInlineJson');
14
15
  const INSTALLED = Symbol.for('odatano.pgInlineJson');
@@ -16,7 +17,6 @@ const INSTALLED = Symbol.for('odatano.pgInlineJson');
16
17
  function isInlineRowStream(v) {
17
18
  return v instanceof stream_1.Readable && Array.isArray(v._raw);
18
19
  }
19
- const dbKind = () => String((cds_1.default.env?.requires?.db)?.kind ?? '');
20
20
  async function drain(stream) {
21
21
  const parts = [];
22
22
  for await (const part of stream)
@@ -30,7 +30,7 @@ function installPostgresInlineJson() {
30
30
  PostgresService = require('@cap-js/postgres/lib/PostgresService');
31
31
  }
32
32
  catch (err) {
33
- if (dbKind() === 'postgres')
33
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
34
34
  logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, bulk writes keep the COPY buffer: ${String(err?.message ?? err)}`);
35
35
  return false;
36
36
  }
@@ -51,7 +51,7 @@ function installPostgresInlineJson() {
51
51
  })();
52
52
  };
53
53
  proto[INSTALLED] = true;
54
- if (dbKind() === 'postgres')
54
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
55
55
  logger.info('Bulk writes on Postgres: row lists sent inline, no COPY buffer');
56
56
  return true;
57
57
  }
@@ -8,9 +8,9 @@ exports.installPostgresOrderNulls = installPostgresOrderNulls;
8
8
  // Drops the NULLS clause from ORDER BY on PostgreSQL for columns that cannot be NULL.
9
9
  // The driver's NULLS placement is the opposite of the btree index, so `$top` would sort the whole table.
10
10
  const cds_1 = __importDefault(require("@sap/cds"));
11
+ const db_kind_1 = require("./db-kind");
11
12
  const logger = cds_1.default.log('PgOrderNulls');
12
13
  const INSTALLED = Symbol.for('odatano.pgOrderNulls');
13
- const dbKind = () => String((cds_1.default.env?.requires?.db)?.kind ?? '');
14
14
  /** Strips the null placement from the rendered terms whose column cannot be NULL. */
15
15
  function stripNullsForNotNull(orderBy, rendered) {
16
16
  return rendered.map((sql, i) => {
@@ -31,7 +31,7 @@ function installPostgresOrderNulls() {
31
31
  }
32
32
  catch (err) {
33
33
  // No loadable Postgres driver: silent unless the database is Postgres.
34
- if (dbKind() === 'postgres')
34
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
35
35
  logger.warn(`@cap-js/postgres/lib/PostgresService not loadable, ORDER BY keeps the NULLS clause: ${String(err?.message ?? err)}`);
36
36
  return false;
37
37
  }
@@ -47,7 +47,7 @@ function installPostgresOrderNulls() {
47
47
  return stripNullsForNotNull(orderBy, orig.call(this, orderBy, ...rest));
48
48
  };
49
49
  proto[INSTALLED] = true;
50
- if (dbKind() === 'postgres')
50
+ if ((0, db_kind_1.configuredDbKind)() === 'postgres')
51
51
  logger.info('ORDER BY on Postgres: NULLS clause dropped for key and NOT NULL columns');
52
52
  return true;
53
53
  }
@@ -0,0 +1,13 @@
1
+ import { BackendError } from './errors';
2
+ import type { CardanoClient } from '../blockchain/cardano-client';
3
+ import type { Request } from '@sap/cds';
4
+ /** What an operator read on the chain for an unresolved outcome. */
5
+ export type ResolvedOutcome = 'confirmed' | 'failed';
6
+ /** The note a resolution leaves on the record: the outcome, who, when and why. */
7
+ export declare function resolutionNote(outcome: ResolvedOutcome, user: string | undefined, note: string | null | undefined, now?: Date): string;
8
+ /** Refuses a resolution whose txHash names another transaction than the record's. */
9
+ export declare function checkResolvedTxHash(req: Request, action: string, given: string | null | undefined, recorded: string | null | undefined): void;
10
+ export declare function refuseFailedWhileItCanLand(action: string, outcome: ResolvedOutcome, signedTxCbor: string | null | undefined, client: Pick<CardanoClient, 'readLedger' | 'network'>): Promise<void>;
11
+ /** The 409 for a record another call resolved first. */
12
+ export declare function resolvedConcurrently(action: string): BackendError;
13
+ //# sourceMappingURL=resolution.d.ts.map
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolutionNote = resolutionNote;
4
+ exports.checkResolvedTxHash = checkResolvedTxHash;
5
+ exports.refuseFailedWhileItCanLand = refuseFailedWhileItCanLand;
6
+ exports.resolvedConcurrently = resolvedConcurrently;
7
+ const errors_1 = require("./errors");
8
+ const error_codes_1 = require("./error-codes");
9
+ const landing_proof_1 = require("../blockchain/signing/landing-proof");
10
+ /** The note a resolution leaves on the record: the outcome, who, when and why. */
11
+ function resolutionNote(outcome, user, note, now = new Date()) {
12
+ const why = note?.trim() ? `: ${note.trim()}` : '';
13
+ return `${outcome} by ${user ?? 'unknown'} at ${now.toISOString()}${why}`.slice(0, 500);
14
+ }
15
+ /** Refuses a resolution whose txHash names another transaction than the record's. */
16
+ function checkResolvedTxHash(req, action, given, recorded) {
17
+ if (given && given.toLowerCase() !== (recorded ?? '').toLowerCase()) {
18
+ (0, errors_1.rejectInvalid)(req, action, `txHash ${given} is not the transaction of this record (${recorded ?? 'none'})`, 'txHash');
19
+ }
20
+ }
21
+ // A failed outcome needs bytes that can no longer land. A landing spends every input, so one spent
22
+ // input already rules it out; while every input is unspent and the bytes are not expired, they can
23
+ // still land, and failed is refused. Read before the request takes its connection.
24
+ async function refuseFailedWhileItCanLand(action, outcome, signedTxCbor, client) {
25
+ if (outcome !== 'failed' || !signedTxCbor || (0, landing_proof_1.isExpired)(signedTxCbor, client.network))
26
+ return;
27
+ let inputs;
28
+ try {
29
+ inputs = (0, landing_proof_1.landingFacts)(signedTxCbor).inputs;
30
+ }
31
+ catch {
32
+ return; // unreadable bytes cannot be sent either
33
+ }
34
+ if (!inputs.length)
35
+ return;
36
+ // an outpoint the backend does not know reads as spent
37
+ const { unspent } = await client.readLedger(inputs);
38
+ if (inputs.every((_, i) => unspent[i] === true)) {
39
+ throw new errors_1.BackendError(`${action}: the transaction can still land, every input it spends is unspent. ` +
40
+ 'Resolve it as failed once one of them is spent by another transaction', 409, error_codes_1.ERROR_CODES.OUTCOME_STILL_OPEN);
41
+ }
42
+ }
43
+ /** The 409 for a record another call resolved first. */
44
+ function resolvedConcurrently(action) {
45
+ return new errors_1.BackendError(`${action}: the record was resolved concurrently`, 409, error_codes_1.ERROR_CODES.RESOLVED_CONCURRENTLY);
46
+ }
47
+ //# sourceMappingURL=resolution.js.map
@@ -0,0 +1,7 @@
1
+ /** The number in `v`, or null when the column is empty or not a number. */
2
+ export declare function optionalNum(v: unknown): number | null;
3
+ /** The number in `v`, or `fallback` when the column is empty or not a number. */
4
+ export declare function requiredNum(v: unknown, fallback?: number): number;
5
+ /** A timestamp column as ISO text, or null when empty. */
6
+ export declare function timestamp(v: unknown): string | null;
7
+ //# sourceMappingURL=row-values.d.ts.map
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ // Database reads return Int64 and Decimal as text and timestamps in the adapter's own form.
3
+ // These turn a column value into the type the code works with.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.optionalNum = optionalNum;
6
+ exports.requiredNum = requiredNum;
7
+ exports.timestamp = timestamp;
8
+ /** The number in `v`, or null when the column is empty or not a number. */
9
+ function optionalNum(v) {
10
+ if (v === null || v === undefined || v === '')
11
+ return null;
12
+ const n = Number(v);
13
+ return Number.isNaN(n) ? null : n;
14
+ }
15
+ /** The number in `v`, or `fallback` when the column is empty or not a number. */
16
+ function requiredNum(v, fallback = 0) {
17
+ return optionalNum(v) ?? fallback;
18
+ }
19
+ /** A timestamp column as ISO text, or null when empty. */
20
+ function timestamp(v) {
21
+ if (v === null || v === undefined || v === '')
22
+ return null;
23
+ if (v instanceof Date)
24
+ return v.toISOString();
25
+ return String(v);
26
+ }
27
+ //# sourceMappingURL=row-values.js.map
@@ -18,6 +18,21 @@ export interface TxCacheTargets {
18
18
  }>;
19
19
  /** Distinct bech32 addresses receiving outputs (sender change + recipients). */
20
20
  outputAddresses: string[];
21
+ /** Outputs of the transaction, every address kind included. */
22
+ outputCount: number;
23
+ /** Last slot in which the transaction is valid (body key 3); null without an expiry. */
24
+ ttlSlot: number | null;
25
+ /** First slot in which the transaction is valid (body key 8); null without a start. */
26
+ validityStartSlot: number | null;
27
+ /** False when the transaction is marked to fail its scripts: then only its collateral is spent. */
28
+ isValid: boolean;
29
+ /** Collateral inputs (body key 13), spent instead of the inputs when the scripts fail. */
30
+ collateralInputs: Array<{
31
+ txHash: string;
32
+ outputIndex: number;
33
+ }>;
34
+ /** Whether the body names a collateral return (key 16). It is output `outputCount` when the scripts fail. */
35
+ hasCollateralReturn: boolean;
21
36
  }
22
37
  export declare function extractTxCacheTargets(txCbor: string): TxCacheTargets;
23
38
  export declare function mapBuilderError(err: unknown, assetUnit?: string, context?: string, requestedOutputs?: number): never;
@@ -62,34 +62,42 @@ function getTxHashFromCbor(txCbor) {
62
62
  // Outputs with undecodable Byron addresses are skipped.
63
63
  function extractTxCacheTargets(txCbor) {
64
64
  let body;
65
+ let isValid = true;
65
66
  try {
66
67
  const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
67
68
  if (!(tx instanceof cbor_1.CborArray) || !(tx.array[0] instanceof cbor_1.CborMap)) {
68
69
  throw new Error('not a transaction');
69
70
  }
70
71
  body = tx.array[0];
72
+ // [body, witnesses, isValid, auxiliary data] since Alonzo; a body alone has no flag
73
+ const flag = tx.array.length === 4 ? tx.array[2] : undefined;
74
+ if (flag instanceof cbor_1.CborSimple && flag.simple === false)
75
+ isValid = false;
71
76
  }
72
77
  catch (err) {
73
78
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
74
79
  }
75
80
  const bodyValue = (key) => body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v;
76
- // key 0: inputs, plain array or CBOR tag-258 set (Conway)
77
- const inputs = [];
78
- let inputsObj = bodyValue(0);
79
- if (inputsObj instanceof cbor_1.CborTag)
80
- inputsObj = inputsObj.data;
81
- if (inputsObj instanceof cbor_1.CborArray) {
82
- for (const entry of inputsObj.array) {
83
- if (entry instanceof cbor_1.CborArray &&
84
- entry.array[0] instanceof cbor_1.CborBytes &&
85
- entry.array[1] instanceof cbor_1.CborUInt) {
86
- inputs.push({ txHash: (0, uint8array_utils_1.toHex)(entry.array[0].bytes), outputIndex: Number(entry.array[1].num) });
81
+ // keys 0 and 13: inputs and collateral inputs, plain array or CBOR tag-258 set (Conway)
82
+ const outRefs = (key) => {
83
+ const refs = [];
84
+ let set = bodyValue(key);
85
+ if (set instanceof cbor_1.CborTag)
86
+ set = set.data;
87
+ if (!(set instanceof cbor_1.CborArray))
88
+ return refs;
89
+ for (const entry of set.array) {
90
+ if (entry instanceof cbor_1.CborArray && entry.array[0] instanceof cbor_1.CborBytes && entry.array[1] instanceof cbor_1.CborUInt) {
91
+ refs.push({ txHash: (0, uint8array_utils_1.toHex)(entry.array[0].bytes), outputIndex: Number(entry.array[1].num) });
87
92
  }
88
93
  }
89
- }
94
+ return refs;
95
+ };
96
+ const inputs = outRefs(0);
90
97
  // key 1: outputs, post-Alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
91
98
  const outputAddresses = new Set();
92
99
  const outputsObj = bodyValue(1);
100
+ const outputCount = outputsObj instanceof cbor_1.CborArray ? outputsObj.array.length : 0;
93
101
  if (outputsObj instanceof cbor_1.CborArray) {
94
102
  for (const output of outputsObj.array) {
95
103
  const addrObj = output instanceof cbor_1.CborMap
@@ -105,7 +113,14 @@ function extractTxCacheTargets(txCbor) {
105
113
  }
106
114
  }
107
115
  }
108
- return { inputs, outputAddresses: [...outputAddresses] };
116
+ const ttl = bodyValue(3);
117
+ const ttlSlot = ttl instanceof cbor_1.CborUInt ? Number(ttl.num) : null;
118
+ const start = bodyValue(8);
119
+ const validityStartSlot = start instanceof cbor_1.CborUInt ? Number(start.num) : null;
120
+ return {
121
+ inputs, outputAddresses: [...outputAddresses], outputCount, ttlSlot, validityStartSlot,
122
+ isValid, collateralInputs: outRefs(13), hasCollateralReturn: bodyValue(16) !== undefined,
123
+ };
109
124
  }
110
125
  // Maps Buildooor errors to typed BackendErrors. `context` is appended to the message.
111
126
  // `requestedOutputs` counts the caller's outputs. Buildooor appends the change after them.