@keetanetwork/anchor 0.0.81 → 0.0.83

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 (52) hide show
  1. package/lib/anchor-metadata-server.js +1 -1
  2. package/lib/anchor-metadata-server.js.map +1 -1
  3. package/lib/anchor-status.d.ts +32 -1
  4. package/lib/anchor-status.d.ts.map +1 -1
  5. package/lib/anchor-status.js +62 -1
  6. package/lib/anchor-status.js.map +1 -1
  7. package/lib/asset.d.ts +3 -0
  8. package/lib/asset.d.ts.map +1 -1
  9. package/lib/asset.js +25 -1
  10. package/lib/asset.js.map +1 -1
  11. package/lib/chaining.d.ts +13 -1
  12. package/lib/chaining.d.ts.map +1 -1
  13. package/lib/chaining.js +58 -17
  14. package/lib/chaining.js.map +1 -1
  15. package/lib/encrypted-container.d.ts.map +1 -1
  16. package/lib/encrypted-container.js +22 -7
  17. package/lib/encrypted-container.js.map +1 -1
  18. package/lib/history.d.ts +77 -21
  19. package/lib/history.d.ts.map +1 -1
  20. package/lib/history.js +951 -70
  21. package/lib/history.js.map +1 -1
  22. package/lib/http-server/index.d.ts.map +1 -1
  23. package/lib/http-server/index.js +20 -1
  24. package/lib/http-server/index.js.map +1 -1
  25. package/lib/index.d.ts +4 -4
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +2 -2
  28. package/lib/index.js.map +1 -1
  29. package/lib/resolver.d.ts.map +1 -1
  30. package/lib/resolver.js +18 -2
  31. package/lib/resolver.js.map +1 -1
  32. package/lib/sensitive-attribute.d.ts.map +1 -1
  33. package/lib/sensitive-attribute.js +24 -2
  34. package/lib/sensitive-attribute.js.map +1 -1
  35. package/npm-shrinkwrap.json +18 -6
  36. package/package.json +2 -1
  37. package/services/fx/client.d.ts +18 -4
  38. package/services/fx/client.d.ts.map +1 -1
  39. package/services/fx/client.js +52 -6
  40. package/services/fx/client.js.map +1 -1
  41. package/services/fx/common.d.ts +35 -0
  42. package/services/fx/common.d.ts.map +1 -1
  43. package/services/fx/common.js +5 -5
  44. package/services/fx/common.js.map +1 -1
  45. package/services/fx/server.d.ts +17 -1
  46. package/services/fx/server.d.ts.map +1 -1
  47. package/services/fx/server.js +236 -18
  48. package/services/fx/server.js.map +1 -1
  49. package/services/fx/status-source.d.ts +34 -0
  50. package/services/fx/status-source.d.ts.map +1 -0
  51. package/services/fx/status-source.js +99 -0
  52. package/services/fx/status-source.js.map +1 -0
package/lib/history.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { lib as KeetaNetLib } from '@keetanetwork/keetanet-client';
2
2
  import { isCompletedTransferStatus } from './anchor-status.js';
3
+ import { AnchorExternal } from './anchor-external.js';
3
4
  import { convertAssetSearchInputToCanonical, isChainLocation, toAssetLocationFromString, toAssetPair } from '../services/asset-movement/common.js';
4
5
  const OperationType = KeetaNetLib.Block.OperationType;
5
6
  /**
@@ -30,7 +31,7 @@ function locationIsChain(location, chainType) {
30
31
  /**
31
32
  * Derive the logical type of an anchor transfer from its endpoints.
32
33
  */
33
- export function logicalTypeFromTransfer(transfer) {
34
+ function logicalTypeFromTransfer(transfer) {
34
35
  const fromKeeta = locationIsChain(transfer.from.location, 'keeta');
35
36
  const toKeeta = locationIsChain(transfer.to.location, 'keeta');
36
37
  if (fromKeeta && toKeeta) {
@@ -53,7 +54,7 @@ export function logicalTypeFromTransfer(transfer) {
53
54
  * Map an anchor transfer's raw status onto the standardized status, carrying
54
55
  * the raw provider string for the wallet to interpret.
55
56
  */
56
- export function statusFromTransfer(transfer) {
57
+ function statusFromTransfer(transfer) {
57
58
  if (isCompletedTransferStatus(transfer.status)) {
58
59
  return ({ status: 'complete', providerStatus: transfer.status });
59
60
  }
@@ -214,6 +215,71 @@ function blockExternals(block) {
214
215
  }
215
216
  return (externals);
216
217
  }
218
+ /**
219
+ * Decode a block's SEND `external` envelopes into the on-chain `inputs` they
220
+ * declare and the anchor transfers they name. Both are captured locally,
221
+ * independent of anchor status resolution; undecodable envelopes are skipped.
222
+ */
223
+ async function decodeExternalEnvelopes(externals, decryptionKeys) {
224
+ const inputs = [];
225
+ const declaredAnchors = [];
226
+ for (const external of externals) {
227
+ let decoded;
228
+ try {
229
+ const decodeOptions = {};
230
+ if (decryptionKeys !== undefined) {
231
+ decodeOptions.decryptionKeys = decryptionKeys;
232
+ }
233
+ decoded = await AnchorExternal.fromExternal(external, decodeOptions);
234
+ }
235
+ catch {
236
+ continue;
237
+ }
238
+ const envelopeInputs = decoded.envelope.inputs;
239
+ if (envelopeInputs !== undefined) {
240
+ for (const inputReference of envelopeInputs) {
241
+ inputs.push(inputReference);
242
+ }
243
+ }
244
+ const signerID = decoded.signed?.signer.publicKeyString.get();
245
+ for (const [anchorID, entry] of Object.entries(decoded.envelope.anchors)) {
246
+ if (!('transactionId' in entry)) {
247
+ continue;
248
+ }
249
+ declaredAnchors.push({ anchorID, transactionID: entry.transactionId, signed: signerID === anchorID });
250
+ }
251
+ }
252
+ return ({ inputs, declaredAnchors });
253
+ }
254
+ /**
255
+ * The single anchor a block's trusted declarations name, or `undefined` when
256
+ * there are none or they disagree.
257
+ */
258
+ function declaredAnchorID(block) {
259
+ const refs = block.declaredAnchors ?? [];
260
+ const first = refs[0];
261
+ if (first === undefined) {
262
+ return (undefined);
263
+ }
264
+ for (const ref of refs) {
265
+ if (ref.anchorID !== first.anchorID) {
266
+ return (undefined);
267
+ }
268
+ }
269
+ return (first.anchorID);
270
+ }
271
+ /**
272
+ * The distinct anchor transfer ids a block declares locally, in order.
273
+ */
274
+ function declaredAnchorTxIDsOf(block) {
275
+ const ids = [];
276
+ for (const ref of block.declaredAnchors ?? []) {
277
+ if (!ids.includes(ref.transactionID)) {
278
+ ids.push(ref.transactionID);
279
+ }
280
+ }
281
+ return (ids);
282
+ }
217
283
  /**
218
284
  * Build the refs block for a logical transaction.
219
285
  */
@@ -223,6 +289,13 @@ function buildRefs(block, anchorTxIDs) {
223
289
  if (externals.length > 0) {
224
290
  refs.external = externals;
225
291
  }
292
+ if (block.inputs !== undefined && block.inputs.length > 0) {
293
+ refs.inputs = block.inputs;
294
+ }
295
+ const declaredAnchorTxIDs = declaredAnchorTxIDsOf(block);
296
+ if (declaredAnchorTxIDs.length > 0) {
297
+ refs.declaredAnchorTxIDs = declaredAnchorTxIDs;
298
+ }
226
299
  return (refs);
227
300
  }
228
301
  // #endregion Operation views
@@ -230,7 +303,7 @@ function buildRefs(block, anchorTxIDs) {
230
303
  /**
231
304
  * Build the logical transaction backing one enriched anchor operation.
232
305
  */
233
- function buildAnchorTransaction(block, enriched, transfer) {
306
+ function buildAnchorTransaction(block, enriched, transfer, indexed) {
234
307
  const type = logicalTypeFromTransfer(transfer);
235
308
  const fromKeeta = locationIsChain(transfer.from.location, 'keeta');
236
309
  const direction = directionFromTransfer(type, fromKeeta);
@@ -255,13 +328,9 @@ function buildAnchorTransaction(block, enriched, transfer) {
255
328
  transactionID: transfer.id,
256
329
  subTransactions: collectAnchorSubTransactions(transfer)
257
330
  });
258
- const refs = { blockHashes: [block.blockHash], anchorTxIDs: [transfer.id] };
259
- const externals = blockExternals(block);
260
- if (externals.length > 0) {
261
- refs.external = externals;
262
- }
331
+ const refs = buildRefs(block, [transfer.id]);
263
332
  const transaction = {
264
- id: `${block.blockHash}:${enriched.index}`,
333
+ id: indexed ? `${block.blockHash}:${enriched.index}` : block.blockHash,
265
334
  type,
266
335
  status: settled.status,
267
336
  providerStatus: settled.providerStatus,
@@ -284,20 +353,88 @@ function buildAnchorTransaction(block, enriched, transfer) {
284
353
  */
285
354
  const anchorTransferClassifier = {
286
355
  classify(block) {
287
- const transactions = [];
356
+ const resolved = [];
288
357
  for (const enriched of block.operations) {
289
358
  const transfer = enriched.transfer;
290
- if (transfer === undefined) {
291
- continue;
359
+ if (transfer !== undefined) {
360
+ resolved.push({ enriched, transfer });
292
361
  }
293
- transactions.push(buildAnchorTransaction(block, enriched, transfer));
294
362
  }
295
- if (transactions.length === 0) {
363
+ if (resolved.length === 0) {
296
364
  return (null);
297
365
  }
298
- return (transactions);
366
+ /*
367
+ * Suffix the id with the operation index only when the block settles more
368
+ * than one transfer; a single-transfer block keeps the bare block hash so
369
+ * its id matches the shape-classified (unenriched) row for the same block.
370
+ */
371
+ const indexed = resolved.length > 1;
372
+ return (resolved.map(entry => buildAnchorTransaction(block, entry.enriched, entry.transfer, indexed)));
299
373
  }
300
374
  };
375
+ /**
376
+ * Pick the swap principal: the largest send whose token differs from the
377
+ * received token.
378
+ */
379
+ function principalSend(sends, receivedToken) {
380
+ let principal;
381
+ for (const send of sends) {
382
+ if (send.amount.token === receivedToken) {
383
+ continue;
384
+ }
385
+ if (principal === undefined || send.amount.amount > principal.amount.amount) {
386
+ principal = send;
387
+ }
388
+ }
389
+ return (principal);
390
+ }
391
+ /**
392
+ * Sum amounts into one total, or `undefined` when there are none or they use
393
+ * more than one token.
394
+ */
395
+ function combineFees(fees) {
396
+ const first = fees.at(0);
397
+ if (first === undefined) {
398
+ return (undefined);
399
+ }
400
+ let total = 0n;
401
+ for (const fee of fees) {
402
+ if (fee.token !== first.token) {
403
+ return (undefined);
404
+ }
405
+ total += fee.amount;
406
+ }
407
+ return ({ token: first.token, amount: total });
408
+ }
409
+ /**
410
+ * Aggregate the non-principal sends into a single fee amount, or `undefined`
411
+ * when there are none or they use more than one token.
412
+ */
413
+ function aggregateFee(feeSends) {
414
+ return (combineFees(feeSends.map(send => send.amount)));
415
+ }
416
+ /**
417
+ * Build a `self`-directed swap from its principal and received legs. Shared by
418
+ * the single-block classifier and the cross-block accepted-swap fold.
419
+ */
420
+ function swapTransaction(input) {
421
+ const transaction = {
422
+ id: input.id,
423
+ type: 'swap',
424
+ status: 'complete',
425
+ direction: 'self',
426
+ timestamp: input.timestamp,
427
+ send: input.send,
428
+ receive: input.receive,
429
+ counterparty: input.counterparty,
430
+ legs: input.legs,
431
+ refs: input.refs
432
+ };
433
+ if (input.fee !== undefined) {
434
+ transaction.fee = input.fee;
435
+ }
436
+ return (transaction);
437
+ }
301
438
  /**
302
439
  * Classifies an on-chain atomic swap: SEND(s) and RECEIVE(s) against a single
303
440
  * counterparty with differing send/receive tokens.
@@ -316,27 +453,21 @@ const atomicSwapClassifier = {
316
453
  if (received === undefined) {
317
454
  return (null);
318
455
  }
319
- const principal = sends.find(send => send.amount.token !== received.amount.token);
456
+ const principal = principalSend(sends, received.amount.token);
320
457
  if (principal === undefined) {
321
458
  return (null);
322
459
  }
323
- const fee = sends.find(send => send.index !== principal.index);
324
- const transaction = {
325
- id: block.blockHash,
326
- type: 'swap',
327
- status: 'complete',
328
- direction: 'self',
329
- timestamp: block.timestamp,
330
- send: principal.amount,
331
- receive: received.amount,
332
- counterparty: { kind: 'liquidity', id: counterparty },
333
- legs: onchainLegs(block),
334
- refs: buildRefs(block, [])
335
- };
336
- if (fee !== undefined) {
337
- transaction.fee = fee.amount;
338
- }
339
- return ([transaction]);
460
+ const fee = aggregateFee(sends.filter(send => send.index !== principal.index));
461
+ return ([swapTransaction({
462
+ id: block.blockHash,
463
+ timestamp: block.timestamp,
464
+ send: principal.amount,
465
+ receive: received.amount,
466
+ counterparty: { kind: 'liquidity', id: counterparty },
467
+ legs: onchainLegs(block),
468
+ refs: buildRefs(block, []),
469
+ ...(fee !== undefined ? { fee } : {})
470
+ })]);
340
471
  }
341
472
  };
342
473
  /**
@@ -362,9 +493,15 @@ const sendClassifier = {
362
493
  legs: onchainLegs(block),
363
494
  refs: buildRefs(block, [])
364
495
  };
365
- const counterparty = uniformCounterparty(sends);
366
- if (counterparty !== undefined) {
367
- transaction.counterparty = { kind: 'account', id: counterparty };
496
+ const anchorID = declaredAnchorID(block);
497
+ if (anchorID !== undefined) {
498
+ transaction.counterparty = { kind: 'anchor', id: anchorID };
499
+ }
500
+ else {
501
+ const counterparty = uniformCounterparty(sends);
502
+ if (counterparty !== undefined) {
503
+ transaction.counterparty = { kind: 'account', id: counterparty };
504
+ }
368
505
  }
369
506
  return ([transaction]);
370
507
  }
@@ -392,9 +529,15 @@ const receiveClassifier = {
392
529
  legs: onchainLegs(block),
393
530
  refs: buildRefs(block, [])
394
531
  };
395
- const counterparty = uniformCounterparty(receives);
396
- if (counterparty !== undefined) {
397
- transaction.counterparty = { kind: 'account', id: counterparty };
532
+ const anchorID = declaredAnchorID(block);
533
+ if (anchorID !== undefined) {
534
+ transaction.counterparty = { kind: 'anchor', id: anchorID };
535
+ }
536
+ else {
537
+ const counterparty = uniformCounterparty(receives);
538
+ if (counterparty !== undefined) {
539
+ transaction.counterparty = { kind: 'account', id: counterparty };
540
+ }
398
541
  }
399
542
  return ([transaction]);
400
543
  }
@@ -427,12 +570,113 @@ export const defaultClassifiers = [
427
570
  otherClassifier
428
571
  ];
429
572
  /**
430
- * Fold enriched blocks into logical transactions by running the ordered
431
- * classifiers; the first classifier that applies to a block wins.
573
+ * Within a settled staple, drop foreign counterpart blocks whose settlement is
574
+ * already represented by a perspective-owned block.
432
575
  */
433
- export function foldHistory(blocks, classifiers) {
434
- const results = [];
576
+ function suppressCoveredForeignBlocks(blocks) {
577
+ const perspective = blocks.find(block => block.perspective !== undefined)?.perspective;
578
+ if (perspective === undefined) {
579
+ return (blocks);
580
+ }
581
+ const owned = blocks.filter(block => block.account === perspective);
582
+ if (owned.length === 0) {
583
+ return (blocks);
584
+ }
585
+ const covered = new Set();
586
+ for (const block of owned) {
587
+ for (const enriched of block.operations) {
588
+ const counterparty = counterpartyID(enriched.operation);
589
+ if (counterparty !== undefined) {
590
+ covered.add(counterparty);
591
+ }
592
+ }
593
+ }
594
+ const result = blocks.filter(block => block.account === perspective || !covered.has(block.account));
595
+ return (result);
596
+ }
597
+ /**
598
+ * Find a block authored by `counterparty` within the staple that exactly
599
+ * consumes `principal` (a RECEIVE from the perspective for the same token and
600
+ * amount) and pays a different token back to the perspective, returning the
601
+ * received amount and that block. This is the counterpart leg of an accepted
602
+ * P2P swap, whose receive leg the perspective never signs itself.
603
+ */
604
+ function matchSwapCounterpart(blocks, perspective, counterparty, principal, consumed) {
435
605
  for (const block of blocks) {
606
+ if (block.account !== counterparty || consumed.has(block.blockHash)) {
607
+ continue;
608
+ }
609
+ let consumesPrincipal = false;
610
+ let payout;
611
+ for (const enriched of block.operations) {
612
+ const view = operationView(enriched.operation);
613
+ if (view === null || view.counterparty !== perspective) {
614
+ continue;
615
+ }
616
+ if (view.opType === 'receive' && view.amount.token === principal.token && view.amount.amount === principal.amount) {
617
+ consumesPrincipal = true;
618
+ }
619
+ else if (view.opType === 'send' && view.amount.token !== principal.token) {
620
+ payout = view.amount;
621
+ }
622
+ }
623
+ if (consumesPrincipal && payout !== undefined) {
624
+ return ({ block, receive: payout });
625
+ }
626
+ }
627
+ return (undefined);
628
+ }
629
+ /**
630
+ * Fold accepted P2P swaps whose legs span two blocks of one staple: the
631
+ * perspective signs only a SEND (the token it gives) while its RECEIVE lives
632
+ * in the counterparty's block.
633
+ */
634
+ function crossBlockSwaps(blocks) {
635
+ const consumed = new Set();
636
+ const transactions = [];
637
+ const perspective = blocks.find(block => block.perspective !== undefined)?.perspective;
638
+ if (perspective === undefined) {
639
+ return ({ transactions, consumed });
640
+ }
641
+ for (const owned of blocks) {
642
+ if (owned.account !== perspective || consumed.has(owned.blockHash)) {
643
+ continue;
644
+ }
645
+ const { sends, receives, otherCount } = viewsOf(owned);
646
+ const principal = sends[0];
647
+ if (otherCount !== 0 || receives.length !== 0 || sends.length !== 1 || principal === undefined) {
648
+ continue;
649
+ }
650
+ const matched = matchSwapCounterpart(blocks, perspective, principal.counterparty, principal.amount, consumed);
651
+ if (matched === undefined) {
652
+ continue;
653
+ }
654
+ const refs = buildRefs(owned, []);
655
+ refs.blockHashes = [...refs.blockHashes, matched.block.blockHash];
656
+ transactions.push(swapTransaction({
657
+ id: owned.blockHash,
658
+ timestamp: owned.timestamp,
659
+ send: principal.amount,
660
+ receive: matched.receive,
661
+ counterparty: { kind: 'account', id: principal.counterparty },
662
+ legs: [...onchainLegs(owned), ...onchainLegs(matched.block)],
663
+ refs
664
+ }));
665
+ consumed.add(owned.blockHash);
666
+ consumed.add(matched.block.blockHash);
667
+ }
668
+ return ({ transactions, consumed });
669
+ }
670
+ /**
671
+ * Fold enriched blocks into logical transactions. Cross-block accepted swaps
672
+ * are paired first so neither leg is later dropped or split, then the ordered
673
+ * classifiers run per block; the first classifier that applies to a block wins.
674
+ */
675
+ function foldHistory(blocks, classifiers) {
676
+ const { transactions: swaps, consumed } = crossBlockSwaps(blocks);
677
+ const results = [...swaps];
678
+ const remaining = blocks.filter(block => !consumed.has(block.blockHash));
679
+ for (const block of suppressCoveredForeignBlocks(remaining)) {
436
680
  for (const classifier of classifiers) {
437
681
  const classified = classifier.classify(block);
438
682
  if (classified !== null) {
@@ -443,6 +687,420 @@ export function foldHistory(blocks, classifiers) {
443
687
  }
444
688
  return (results);
445
689
  }
690
+ /**
691
+ * Append `value` to `target` only when it is not already present.
692
+ */
693
+ function pushUnique(target, value) {
694
+ if (!target.includes(value)) {
695
+ target.push(value);
696
+ }
697
+ }
698
+ /**
699
+ * Whether `transaction` declares an on-chain input that points at one of the
700
+ * blocks contributing to `candidate`.
701
+ */
702
+ function inputsReference(transaction, candidate) {
703
+ const inputs = transaction.refs.inputs;
704
+ if (inputs === undefined) {
705
+ return (false);
706
+ }
707
+ const blockHashes = new Set(candidate.refs.blockHashes);
708
+ for (const input of inputs) {
709
+ if (blockHashes.has(input.blockHash)) {
710
+ return (true);
711
+ }
712
+ }
713
+ return (false);
714
+ }
715
+ /**
716
+ * The counterparty shared by every hop, or `undefined` when the hops disagree.
717
+ */
718
+ function sharedCounterparty(hops) {
719
+ let shared;
720
+ for (const hop of hops) {
721
+ if (hop.counterparty === undefined) {
722
+ return (undefined);
723
+ }
724
+ if (shared === undefined) {
725
+ shared = hop.counterparty;
726
+ continue;
727
+ }
728
+ if (shared.kind !== hop.counterparty.kind || shared.id !== hop.counterparty.id) {
729
+ return (undefined);
730
+ }
731
+ }
732
+ return (shared);
733
+ }
734
+ /**
735
+ * Merge every hop's `refs`, de-duplicating block hashes, anchor transfer ids
736
+ * and externals while preserving the ordered on-chain inputs.
737
+ */
738
+ function accumulateHopRefs(hops) {
739
+ const merged = { blockHashes: [], anchorTxIDs: [], externals: [], inputs: [], declaredAnchorTxIDs: [] };
740
+ for (const hop of hops) {
741
+ for (const blockHash of hop.refs.blockHashes) {
742
+ pushUnique(merged.blockHashes, blockHash);
743
+ }
744
+ for (const anchorTxID of hop.refs.anchorTxIDs) {
745
+ pushUnique(merged.anchorTxIDs, anchorTxID);
746
+ }
747
+ for (const external of hop.refs.external ?? []) {
748
+ pushUnique(merged.externals, external);
749
+ }
750
+ for (const input of hop.refs.inputs ?? []) {
751
+ merged.inputs.push(input);
752
+ }
753
+ for (const declaredAnchorTxID of hop.refs.declaredAnchorTxIDs ?? []) {
754
+ pushUnique(merged.declaredAnchorTxIDs, declaredAnchorTxID);
755
+ }
756
+ }
757
+ return (merged);
758
+ }
759
+ /**
760
+ * Combine hop statuses with failed taking precedence over pending over
761
+ * complete.
762
+ */
763
+ function aggregateHopStatus(hops) {
764
+ let pending = false;
765
+ for (const hop of hops) {
766
+ if (hop.status === 'failed') {
767
+ return ('failed');
768
+ }
769
+ if (hop.status === 'pending') {
770
+ pending = true;
771
+ }
772
+ }
773
+ return (pending ? 'pending' : 'complete');
774
+ }
775
+ /**
776
+ * The earliest timestamp across the hops, never later than `fallback`.
777
+ */
778
+ function earliestHopTimestamp(hops, fallback) {
779
+ let earliest = fallback;
780
+ for (const hop of hops) {
781
+ if (Date.parse(hop.timestamp) < Date.parse(earliest)) {
782
+ earliest = hop.timestamp;
783
+ }
784
+ }
785
+ return (earliest);
786
+ }
787
+ /**
788
+ * The fees declared by the hops, in chain order.
789
+ */
790
+ function collectHopFees(hops) {
791
+ const fees = [];
792
+ for (const hop of hops) {
793
+ if (hop.fee !== undefined) {
794
+ fees.push(hop.fee);
795
+ }
796
+ }
797
+ return (fees);
798
+ }
799
+ /**
800
+ * The provider status of the latest hop that carries one, so a folded
801
+ * conversion still reports the anchor's settlement status.
802
+ */
803
+ function latestHopProviderStatus(hops) {
804
+ let providerStatus;
805
+ for (const hop of hops) {
806
+ if (hop.providerStatus !== undefined) {
807
+ providerStatus = hop.providerStatus;
808
+ }
809
+ }
810
+ return (providerStatus);
811
+ }
812
+ /**
813
+ * The head's legs followed by the tail's, suppressing intermediate hops and
814
+ * avoiding a duplicate when head and tail are the same transaction.
815
+ */
816
+ function mergeHopLegs(head, tail) {
817
+ const legs = [...head.legs];
818
+ if (tail.id !== head.id) {
819
+ legs.push(...tail.legs);
820
+ }
821
+ return (legs);
822
+ }
823
+ /**
824
+ * The display shape of a folded conversion.
825
+ */
826
+ function conversionShape(head, tail, hops) {
827
+ if (head.type === 'send' && tail.type === 'receive') {
828
+ return ({ type: 'swap', direction: 'self', counterparty: head.counterparty ?? tail.counterparty });
829
+ }
830
+ const counterparty = tail.type === 'swap' ? sharedCounterparty(hops) : tail.counterparty;
831
+ return ({ type: tail.type, direction: tail.direction, counterparty });
832
+ }
833
+ function mergeChainHops(head, tail, hops) {
834
+ const { blockHashes, anchorTxIDs, externals, inputs, declaredAnchorTxIDs } = accumulateHopRefs(hops);
835
+ const refs = { blockHashes, anchorTxIDs };
836
+ if (externals.length > 0) {
837
+ refs.external = externals;
838
+ }
839
+ if (inputs.length > 0) {
840
+ refs.inputs = inputs;
841
+ }
842
+ if (declaredAnchorTxIDs.length > 0) {
843
+ refs.declaredAnchorTxIDs = declaredAnchorTxIDs;
844
+ }
845
+ const shape = conversionShape(head, tail, hops);
846
+ const merged = {
847
+ id: head.id,
848
+ type: shape.type,
849
+ status: aggregateHopStatus(hops),
850
+ direction: shape.direction,
851
+ timestamp: earliestHopTimestamp(hops, head.timestamp),
852
+ legs: mergeHopLegs(head, tail),
853
+ refs
854
+ };
855
+ if (head.send !== undefined) {
856
+ merged.send = head.send;
857
+ }
858
+ if (tail.receive !== undefined) {
859
+ merged.receive = tail.receive;
860
+ }
861
+ const fee = combineFees(collectHopFees(hops));
862
+ if (fee !== undefined) {
863
+ merged.fee = fee;
864
+ }
865
+ if (shape.counterparty !== undefined) {
866
+ merged.counterparty = shape.counterparty;
867
+ }
868
+ const providerStatus = latestHopProviderStatus(hops);
869
+ if (providerStatus !== undefined) {
870
+ merged.providerStatus = providerStatus;
871
+ }
872
+ return (merged);
873
+ }
874
+ /**
875
+ * An unenriched leg attributed to an anchor purely from its locally decoded
876
+ * `external` (a declared transfer id, no authoritative `anchorTxIDs` yet, and
877
+ * an anchor counterparty). These are the hops of an anchor conversion before
878
+ * enrichment resolves their true swap/bridge types, so they chain along their
879
+ * `inputs` edges the way resolved swaps do.
880
+ */
881
+ function isLocalAnchorHop(transaction) {
882
+ return (transaction.refs.anchorTxIDs.length === 0
883
+ && (transaction.refs.declaredAnchorTxIDs?.length ?? 0) > 0
884
+ && transaction.counterparty?.kind === 'anchor');
885
+ }
886
+ /**
887
+ * Whether `head` may fold into `successor` along their
888
+ * `refs.inputs` <-> `refs.blockHashes` link: swaps chain into further swaps or
889
+ * a capping bridge, and a pay-in `send` caps into its delivery `receive`. The
890
+ * single source of truth for edge validity, shared by the pure
891
+ * {@link foldChains} pass and the incremental by-hash resolution.
892
+ */
893
+ function canLink(head, successor) {
894
+ /*
895
+ * Unenriched anchor hops chain to one another along their inputs edges the
896
+ * way resolved swaps do, so a multi-hop anchor conversion folds into one row
897
+ * without enrichment. The inputs edge itself is always separately required
898
+ * by the caller.
899
+ */
900
+ if (isLocalAnchorHop(head) && isLocalAnchorHop(successor)) {
901
+ return (true);
902
+ }
903
+ if (head.type === 'swap') {
904
+ return (successor.type === 'swap' || successor.type === 'bridge');
905
+ }
906
+ if (head.type === 'send') {
907
+ return (successor.type === 'receive');
908
+ }
909
+ return (false);
910
+ }
911
+ function linkChainSuccessors(heads, successors) {
912
+ const successorOf = new Map();
913
+ const predecessorOf = new Map();
914
+ for (const head of heads) {
915
+ for (const other of successors) {
916
+ if (other.id === head.id || successorOf.has(head.id)) {
917
+ continue;
918
+ }
919
+ if (canLink(head, other) && inputsReference(other, head)) {
920
+ successorOf.set(head.id, other);
921
+ predecessorOf.set(other.id, head);
922
+ }
923
+ }
924
+ }
925
+ return ({ successorOf, predecessorOf });
926
+ }
927
+ /**
928
+ * Walk the successor links from `head` to its tail, returning the hops in
929
+ * order and stopping on a cycle.
930
+ */
931
+ function walkChainFrom(head, successorOf) {
932
+ const hops = [head];
933
+ const visited = new Set([head.id]);
934
+ let current = head;
935
+ while (true) {
936
+ const next = successorOf.get(current.id);
937
+ if (next === undefined || visited.has(next.id)) {
938
+ break;
939
+ }
940
+ hops.push(next);
941
+ visited.add(next.id);
942
+ current = next;
943
+ }
944
+ return (hops);
945
+ }
946
+ function buildChains(transactions) {
947
+ const heads = transactions.filter(transaction => transaction.type === 'swap' || transaction.type === 'send' || isLocalAnchorHop(transaction));
948
+ const successors = transactions.filter(transaction => transaction.type === 'swap' || transaction.type === 'bridge' || transaction.type === 'receive' || isLocalAnchorHop(transaction));
949
+ const { successorOf, predecessorOf } = linkChainSuccessors(heads, successors);
950
+ const chainByMemberId = new Map();
951
+ for (const head of heads) {
952
+ if (predecessorOf.has(head.id)) {
953
+ continue;
954
+ }
955
+ const hops = walkChainFrom(head, successorOf);
956
+ const tail = hops.at(-1);
957
+ if (hops.length < 2 || tail === undefined) {
958
+ continue;
959
+ }
960
+ const chain = { id: head.id, head, tail, hops };
961
+ for (const hop of hops) {
962
+ chainByMemberId.set(hop.id, chain);
963
+ }
964
+ }
965
+ return (chainByMemberId);
966
+ }
967
+ /**
968
+ * Fold linked chains into single conversions for display: multi-hop swaps, a
969
+ * swap that funds an outbound bridge, and a pay-in send capped by its delivery
970
+ * receive (a non-atomic anchor swap seen leanly).
971
+ */
972
+ export function foldChains(transactions) {
973
+ const chainByMemberId = buildChains(transactions);
974
+ if (chainByMemberId.size === 0) {
975
+ return ([...transactions]);
976
+ }
977
+ const emittedChains = new Set();
978
+ const result = [];
979
+ for (const transaction of transactions) {
980
+ const chain = chainByMemberId.get(transaction.id);
981
+ if (chain === undefined) {
982
+ result.push(transaction);
983
+ continue;
984
+ }
985
+ if (emittedChains.has(chain.id)) {
986
+ continue;
987
+ }
988
+ emittedChains.add(chain.id);
989
+ result.push(mergeChainHops(chain.head, chain.tail, chain.hops));
990
+ }
991
+ return (result);
992
+ }
993
+ /**
994
+ * The anchor transfer ids a transaction settles: the authoritative
995
+ * `anchorTxIDs` once enriched, otherwise the ids declared locally by the
996
+ * block's `external` so an unenriched list de-duplicates a transfer's several
997
+ * legs the same way. The empty-`anchorTxIDs` gate keeps enriched suppression
998
+ * identical to before.
999
+ */
1000
+ function settlementIDs(transaction) {
1001
+ const refs = transaction.refs;
1002
+ if (refs.anchorTxIDs.length > 0) {
1003
+ return (refs.anchorTxIDs);
1004
+ }
1005
+ return (refs.declaredAnchorTxIDs ?? []);
1006
+ }
1007
+ /**
1008
+ * Whether every anchor transfer a logical transaction settles has already been
1009
+ * emitted, marking it a duplicate settlement leg.
1010
+ */
1011
+ function isSettledDuplicate(transaction, emitted) {
1012
+ const ids = settlementIDs(transaction);
1013
+ if (ids.length === 0) {
1014
+ return (false);
1015
+ }
1016
+ return (ids.every(id => emitted.has(id)));
1017
+ }
1018
+ /**
1019
+ * Record the anchor transfers a logical transaction settles.
1020
+ */
1021
+ function markEmittedTransfers(transaction, emitted) {
1022
+ for (const id of settlementIDs(transaction)) {
1023
+ emitted.add(id);
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Whether a transaction is a settlement leg already accounted for by an
1028
+ * earlier (newest-first) conversion.
1029
+ */
1030
+ function isSettledLeg(transaction, emittedBlocks) {
1031
+ if (transaction.type !== 'receive') {
1032
+ return (false);
1033
+ }
1034
+ const inputs = transaction.refs.inputs;
1035
+ if (inputs === undefined || inputs.length === 0) {
1036
+ return (false);
1037
+ }
1038
+ return (inputs.every(input => emittedBlocks.has(input.blockHash)));
1039
+ }
1040
+ /**
1041
+ * Record the on-chain blocks a logical transaction (or folded conversion)
1042
+ * already accounts for.
1043
+ */
1044
+ function markEmittedBlocks(transaction, emitted) {
1045
+ for (const blockHash of transaction.refs.blockHashes) {
1046
+ emitted.add(blockHash);
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Drop logical transactions whose every settled transfer was already emitted by
1051
+ * an earlier (newest-first) entry, collapsing a transfer's multiple on-chain
1052
+ * legs into the single conversion that represents it.
1053
+ */
1054
+ function suppressSettledDuplicates(transactions) {
1055
+ const emitted = new Set();
1056
+ const emittedBlocks = new Set();
1057
+ const result = [];
1058
+ for (const transaction of transactions) {
1059
+ if (isSettledDuplicate(transaction, emitted) || isSettledLeg(transaction, emittedBlocks)) {
1060
+ continue;
1061
+ }
1062
+ markEmittedTransfers(transaction, emitted);
1063
+ markEmittedBlocks(transaction, emittedBlocks);
1064
+ result.push(transaction);
1065
+ }
1066
+ return (result);
1067
+ }
1068
+ /**
1069
+ * Relabel a lone unenriched anchor leg to its provisional withdraw/deposit
1070
+ * shape for display. A no-op once enriched (the row then carries authoritative
1071
+ * `anchorTxIDs`), for folded swaps, and for rows with no trusted anchor
1072
+ * declaration. Must run AFTER settlement suppression, since it rewrites `type`
1073
+ * and would otherwise defeat the `type === 'receive'` gate in `isSettledLeg`.
1074
+ */
1075
+ function normalizeProvisional(transaction) {
1076
+ const refs = transaction.refs;
1077
+ if (refs.anchorTxIDs.length > 0) {
1078
+ return (transaction);
1079
+ }
1080
+ if (refs.declaredAnchorTxIDs === undefined || refs.declaredAnchorTxIDs.length === 0) {
1081
+ return (transaction);
1082
+ }
1083
+ if (transaction.counterparty?.kind !== 'anchor') {
1084
+ return (transaction);
1085
+ }
1086
+ if (transaction.type !== 'send' && transaction.type !== 'receive') {
1087
+ return (transaction);
1088
+ }
1089
+ return ({ ...transaction, type: transaction.type === 'send' ? 'withdraw' : 'deposit', provisional: true });
1090
+ }
1091
+ /**
1092
+ * Re-attach a caller's `source` to a conversion that lost it. A folded
1093
+ * multi-hop conversion is built fresh by {@link mergeChainHops} and carries no
1094
+ * `source`, so an `includeSource` enrichment would otherwise drop the
1095
+ * perspective a detail view needs. Mirrors how {@link UserHistory.iterate}
1096
+ * carries source into a folded conversion in its `#foldForward` pass.
1097
+ */
1098
+ function attachConversionSource(transaction, source, includeSource) {
1099
+ if (!includeSource || transaction.source !== undefined || source === undefined) {
1100
+ return (transaction);
1101
+ }
1102
+ return ({ ...transaction, source });
1103
+ }
446
1104
  /**
447
1105
  * The first transfer reported as a status across an external's anchors.
448
1106
  */
@@ -527,47 +1185,112 @@ export class UserHistory {
527
1185
  this.#classifiers = config.classifiers ?? defaultClassifiers;
528
1186
  }
529
1187
  /**
530
- * Fetch, enrich and fold a user's history into logical transactions.
1188
+ * Fetch, enrich and fold a user's history into logical transactions,
1189
+ * grouping linked multi-hop chains into single conversions.
531
1190
  */
532
1191
  async list(account, options) {
533
1192
  const transactions = [];
534
- for await (const transaction of this.iterate(account, options)) {
1193
+ /*
1194
+ * When the source can resolve staples by block hash, iterate() already
1195
+ * folds linked chains incrementally and honors `limit` by short-circuit,
1196
+ * so a bounded `limit` no longer walks the whole account.
1197
+ */
1198
+ if (typeof this.#history.getVoteStaple === 'function') {
1199
+ for await (const transaction of this.iterate(account, options)) {
1200
+ transactions.push(transaction);
1201
+ }
1202
+ return (transactions);
1203
+ }
1204
+ /*
1205
+ * Fallback for sources without by-hash resolution: drain fully and fold
1206
+ * across the whole set so cross-page chains still group.
1207
+ */
1208
+ const { limit, ...collectOptions } = options ?? {};
1209
+ for await (const transaction of this.iterate(account, collectOptions)) {
535
1210
  transactions.push(transaction);
536
1211
  }
537
- return (transactions);
1212
+ const folded = suppressSettledDuplicates(foldChains(transactions)).map(normalizeProvisional);
1213
+ if (limit !== undefined) {
1214
+ return (folded.slice(0, limit));
1215
+ }
1216
+ return (folded);
538
1217
  }
539
1218
  /**
540
- * Stream logical transactions page by page instead of buffering the full
541
- * result set in memory.
1219
+ * Enrich a single transaction on demand by resolving the anchor transfers
1220
+ * for only its contributing blocks.
542
1221
  */
543
- async *iterate(account, options) {
1222
+ async enrichTransaction(transaction, account, options) {
1223
+ const source = this.#history;
1224
+ if (typeof source.getVoteStaple !== 'function') {
1225
+ return (transaction);
1226
+ }
1227
+ const perspective = perspectiveOf(account);
1228
+ const resolved = this.#withDefaultDecryptionKeys(account, { ...options, enrich: true });
544
1229
  const externalCache = new Map();
545
1230
  const readerCache = new Map();
546
- const perspective = perspectiveOf(account);
547
- let cursor = options?.cursor;
1231
+ const logical = [];
1232
+ const visited = new Set();
1233
+ for (const blockHash of transaction.refs.blockHashes) {
1234
+ if (visited.has(blockHash)) {
1235
+ continue;
1236
+ }
1237
+ visited.add(blockHash);
1238
+ const staple = await source.getVoteStaple(blockHash);
1239
+ if (staple === null || staple === undefined) {
1240
+ continue;
1241
+ }
1242
+ for (const candidate of await this.#foldStaple(staple, perspective, resolved, externalCache, readerCache)) {
1243
+ logical.push(candidate);
1244
+ }
1245
+ }
1246
+ const blockHashes = new Set(transaction.refs.blockHashes);
1247
+ const folded = foldChains(logical);
1248
+ const includeSource = resolved?.includeSource === true;
1249
+ const matchByID = folded.find(function (candidate) {
1250
+ return (candidate.id === transaction.id);
1251
+ });
1252
+ if (matchByID !== undefined) {
1253
+ return (attachConversionSource(normalizeProvisional(matchByID), transaction.source, includeSource));
1254
+ }
1255
+ const matchByBlock = folded.find(function (candidate) {
1256
+ return (candidate.refs.blockHashes.some(hash => blockHashes.has(hash)));
1257
+ });
1258
+ return (attachConversionSource(normalizeProvisional(matchByBlock ?? transaction), transaction.source, includeSource));
1259
+ }
1260
+ /**
1261
+ * Stream logical transactions newest-first, paging through history one page
1262
+ * at a time instead of buffering the full result set. Walks every page until
1263
+ * history is exhausted, or until {@link UserHistoryListOptions.limit} logical
1264
+ * transactions have been yielded.
1265
+ */
1266
+ async *iterate(account, options) {
1267
+ const resolved = this.#withDefaultDecryptionKeys(account, options);
1268
+ const context = {
1269
+ perspective: perspectiveOf(account),
1270
+ options: resolved,
1271
+ foldCapable: typeof this.#history.getVoteStaple === 'function',
1272
+ consumed: new Set(),
1273
+ emittedTransfers: new Set(),
1274
+ emittedBlocks: new Set(),
1275
+ externalCache: new Map(),
1276
+ readerCache: new Map()
1277
+ };
1278
+ let cursor = resolved?.cursor;
548
1279
  let yielded = 0;
549
1280
  while (true) {
550
- const page = await this.#fetchPage(account, cursor, options);
1281
+ const page = await this.#fetchPage(account, cursor, resolved);
551
1282
  if (page.length === 0) {
552
1283
  return;
553
1284
  }
554
1285
  for (const entry of page) {
555
- const timestamp = entry.voteStaple.timestamp().toISOString();
556
- const blocks = [];
557
- const sources = new Map();
558
- for (const block of entry.voteStaple.blocks) {
559
- const enriched = await this.#enrichBlock(block, timestamp, perspective, options, externalCache, readerCache);
560
- blocks.push(enriched);
561
- if (options?.includeSource === true) {
562
- sources.set(enriched.blockHash, { staple: entry.voteStaple, enriched });
1286
+ for (const transaction of await this.#stapleEmissions(entry.voteStaple, context)) {
1287
+ const out = await this.#nextEmission(transaction, context);
1288
+ if (out === undefined) {
1289
+ continue;
563
1290
  }
564
- }
565
- const logical = foldHistory(blocks, this.#classifiers);
566
- attachSources(logical, sources);
567
- for (const transaction of logical) {
568
- yield transaction;
1291
+ yield out;
569
1292
  yielded += 1;
570
- if (options?.limit !== undefined && yielded >= options.limit) {
1293
+ if (resolved?.limit !== undefined && yielded >= resolved.limit) {
571
1294
  return;
572
1295
  }
573
1296
  }
@@ -577,10 +1300,147 @@ export class UserHistory {
577
1300
  return;
578
1301
  }
579
1302
  cursor = last.voteStaple.blocksHash.toString();
580
- if (options?.limit === undefined) {
581
- return;
1303
+ }
1304
+ }
1305
+ /**
1306
+ * Classify a staple into the logical transactions to consider, folding
1307
+ * chains up front when the source supports it.
1308
+ */
1309
+ async #stapleEmissions(staple, context) {
1310
+ const logical = await this.#foldStaple(staple, context.perspective, context.options, context.externalCache, context.readerCache);
1311
+ return (context.foldCapable ? foldChains(logical) : logical);
1312
+ }
1313
+ /**
1314
+ * Resolve a candidate to the transaction that should be emitted, or
1315
+ * `undefined` when it is an already-consumed hop or a duplicate settlement
1316
+ * leg. Folds the candidate forward and records what it settles.
1317
+ */
1318
+ async #nextEmission(transaction, context) {
1319
+ if (context.consumed.has(transaction.id)) {
1320
+ return (undefined);
1321
+ }
1322
+ let out = transaction;
1323
+ if (context.foldCapable) {
1324
+ out = await this.#foldForward(transaction, context.consumed, context.perspective, context.options, context.externalCache, context.readerCache);
1325
+ }
1326
+ if (isSettledDuplicate(out, context.emittedTransfers) || isSettledLeg(out, context.emittedBlocks)) {
1327
+ return (undefined);
1328
+ }
1329
+ markEmittedTransfers(out, context.emittedTransfers);
1330
+ markEmittedBlocks(out, context.emittedBlocks);
1331
+ return (context.foldCapable ? normalizeProvisional(out) : out);
1332
+ }
1333
+ /**
1334
+ * Default {@link UserHistoryListOptions.decryptionKeys} to the queried
1335
+ * account, the recipient of any anchor-delivered slice and so the natural
1336
+ * key for the externals encrypted to it. An explicit `decryptionKeys` (or a
1337
+ * string/null perspective that cannot decrypt) is left untouched.
1338
+ */
1339
+ #withDefaultDecryptionKeys(account, options) {
1340
+ if (options?.decryptionKeys !== undefined || account === null || typeof account === 'string') {
1341
+ return (options);
1342
+ }
1343
+ return ({ ...options, decryptionKeys: [account] });
1344
+ }
1345
+ /**
1346
+ * Enrich and classify a single vote staple's blocks into logical
1347
+ * transactions, attaching raw sources when requested. Shared by the paging
1348
+ * loop and the by-hash predecessor resolution used to fold chains.
1349
+ */
1350
+ async #foldStaple(staple, perspective, options, externalCache, readerCache) {
1351
+ const timestamp = staple.timestamp().toISOString();
1352
+ const blocks = [];
1353
+ const sources = new Map();
1354
+ for (const block of staple.blocks) {
1355
+ const enriched = await this.#enrichBlock(block, timestamp, perspective, options, externalCache, readerCache);
1356
+ blocks.push(enriched);
1357
+ if (options?.includeSource === true) {
1358
+ sources.set(enriched.blockHash, { staple, enriched });
1359
+ }
1360
+ }
1361
+ const logical = foldHistory(blocks, this.#classifiers);
1362
+ attachSources(logical, sources);
1363
+ return (logical);
1364
+ }
1365
+ /**
1366
+ * Fold a tail that declares on-chain inputs into the full conversion it
1367
+ * caps, resolving every linked predecessor by hash and marking each hop
1368
+ * `consumed` so it is skipped when it later pages in.
1369
+ */
1370
+ async #foldForward(transaction, consumed, perspective, options, externalCache, readerCache) {
1371
+ const foldable = transaction.type === 'swap' || transaction.type === 'bridge' || transaction.type === 'receive' || isLocalAnchorHop(transaction);
1372
+ if (!foldable || transaction.refs.inputs === undefined || transaction.refs.inputs.length === 0) {
1373
+ return (transaction);
1374
+ }
1375
+ const hops = await this.#resolveChainBackward(transaction, perspective, options, externalCache, readerCache);
1376
+ const head = hops.at(0);
1377
+ const tail = hops.at(-1);
1378
+ if (hops.length < 2 || head === undefined || tail === undefined) {
1379
+ return (transaction);
1380
+ }
1381
+ for (const hop of hops) {
1382
+ consumed.add(hop.id);
1383
+ }
1384
+ const merged = mergeChainHops(head, tail, hops);
1385
+ if (options?.includeSource === true && transaction.source !== undefined) {
1386
+ merged.source = transaction.source;
1387
+ }
1388
+ return (merged);
1389
+ }
1390
+ /**
1391
+ * Walk a chain backward from its tail, following each hop's on-chain input
1392
+ * to the predecessor it references, until the head (a hop with no
1393
+ * resolvable input) is reached. Returns the hops oldest-first.
1394
+ */
1395
+ async #resolveChainBackward(tail, perspective, options, externalCache, readerCache) {
1396
+ const hops = [tail];
1397
+ const seenIds = new Set([tail.id]);
1398
+ const triedHashes = new Set();
1399
+ let current = tail;
1400
+ while (true) {
1401
+ const predecessor = await this.#walkToPredecessor(current, triedHashes, seenIds, perspective, options, externalCache, readerCache);
1402
+ if (predecessor === undefined) {
1403
+ break;
582
1404
  }
1405
+ hops.unshift(predecessor);
1406
+ seenIds.add(predecessor.id);
1407
+ current = predecessor;
583
1408
  }
1409
+ return (hops);
1410
+ }
1411
+ /**
1412
+ * Resolve the first not-yet-tried input of `current` to the predecessor it
1413
+ * references, or `undefined` when none resolve to a new, linkable hop.
1414
+ */
1415
+ async #walkToPredecessor(current, triedHashes, seenIds, perspective, options, externalCache, readerCache) {
1416
+ for (const input of current.refs.inputs ?? []) {
1417
+ if (triedHashes.has(input.blockHash)) {
1418
+ continue;
1419
+ }
1420
+ triedHashes.add(input.blockHash);
1421
+ const predecessor = await this.#resolveContributing(input.blockHash, current, perspective, options, externalCache, readerCache);
1422
+ if (predecessor !== undefined && !seenIds.has(predecessor.id)) {
1423
+ return (predecessor);
1424
+ }
1425
+ }
1426
+ return (undefined);
1427
+ }
1428
+ /**
1429
+ * Fetch the staple settling `blockHash` and return the logical transaction
1430
+ * it contributes that may fold into `successor` (per {@link canLink}), or
1431
+ * `undefined` when none can be resolved.
1432
+ */
1433
+ async #resolveContributing(blockHash, successor, perspective, options, externalCache, readerCache) {
1434
+ const source = this.#history;
1435
+ if (typeof source.getVoteStaple !== 'function') {
1436
+ return (undefined);
1437
+ }
1438
+ const staple = await source.getVoteStaple(blockHash);
1439
+ if (staple === null || staple === undefined) {
1440
+ return (undefined);
1441
+ }
1442
+ const logical = foldChains(await this.#foldStaple(staple, perspective, options, externalCache, readerCache));
1443
+ return (logical.find(transaction => transaction.refs.blockHashes.includes(blockHash) && canLink(transaction, successor)));
584
1444
  }
585
1445
  /**
586
1446
  * Fetch one page of on-chain history.
@@ -605,7 +1465,12 @@ export class UserHistory {
605
1465
  async #enrichBlock(block, timestamp, perspective, options, externalCache, readerCache) {
606
1466
  const blockHash = block.hash.toString();
607
1467
  const account = block.account.publicKeyString.get();
608
- const enrichEnabled = options?.enrich !== false && this.#status !== undefined;
1468
+ const enrichEnabled = options?.enrich === true && this.#status !== undefined;
1469
+ /*
1470
+ * A single anchor transfer (an FX swap, say) can be settled by several
1471
+ * operations in one block.
1472
+ */
1473
+ const attachedTransferIDs = new Set();
609
1474
  const operations = [];
610
1475
  for (let index = 0; index < block.operations.length; index++) {
611
1476
  const operation = block.operations[index];
@@ -615,7 +1480,8 @@ export class UserHistory {
615
1480
  const enriched = { operation, index };
616
1481
  if (enrichEnabled) {
617
1482
  const resolved = await this.#resolveTransfer(block, operation, index, perspective, options, externalCache, readerCache);
618
- if (resolved !== undefined) {
1483
+ if (resolved !== undefined && !attachedTransferIDs.has(resolved.transfer.id)) {
1484
+ attachedTransferIDs.add(resolved.transfer.id);
619
1485
  enriched.transfer = resolved.transfer;
620
1486
  enriched.anchorID = resolved.anchorID;
621
1487
  }
@@ -626,6 +1492,21 @@ export class UserHistory {
626
1492
  if (perspective !== undefined) {
627
1493
  result.perspective = perspective;
628
1494
  }
1495
+ const decoded = await decodeExternalEnvelopes(blockExternals(result), options?.decryptionKeys);
1496
+ if (decoded.inputs.length > 0) {
1497
+ result.inputs = decoded.inputs;
1498
+ }
1499
+ /*
1500
+ * Only trust a declared anchor reference when the block is issued by the
1501
+ * perspective (its own history) or the entry was signed by the anchor.
1502
+ * An unsigned foreign block could otherwise assert a transfer id it does
1503
+ * not own and corrupt grouping.
1504
+ */
1505
+ const owned = perspective !== undefined && account === perspective;
1506
+ const trustedAnchors = decoded.declaredAnchors.filter(ref => owned || ref.signed);
1507
+ if (trustedAnchors.length > 0) {
1508
+ result.declaredAnchors = trustedAnchors;
1509
+ }
629
1510
  return (result);
630
1511
  }
631
1512
  /**