@keetanetwork/anchor 0.0.85 → 0.0.87

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 (39) hide show
  1. package/lib/asset.d.ts +2 -0
  2. package/lib/asset.d.ts.map +1 -1
  3. package/lib/asset.js +4 -0
  4. package/lib/asset.js.map +1 -1
  5. package/lib/chaining.d.ts +106 -6
  6. package/lib/chaining.d.ts.map +1 -1
  7. package/lib/chaining.js +705 -247
  8. package/lib/chaining.js.map +1 -1
  9. package/lib/queue/index.d.ts.map +1 -1
  10. package/lib/queue/index.js +7 -6
  11. package/lib/queue/index.js.map +1 -1
  12. package/lib/resolver.d.ts.map +1 -1
  13. package/lib/resolver.js +128 -90
  14. package/lib/resolver.js.map +1 -1
  15. package/npm-shrinkwrap.json +2 -2
  16. package/package.json +1 -1
  17. package/services/asset-movement/client.js +1 -1
  18. package/services/asset-movement/client.js.map +1 -1
  19. package/services/asset-movement/common.d.ts +10 -4
  20. package/services/asset-movement/common.d.ts.map +1 -1
  21. package/services/asset-movement/common.js +16 -3
  22. package/services/asset-movement/common.js.map +1 -1
  23. package/services/asset-movement/common.server.generated.js +47 -12
  24. package/services/asset-movement/common.server.generated.js.map +1 -1
  25. package/services/storage/client.d.ts +12 -1
  26. package/services/storage/client.d.ts.map +1 -1
  27. package/services/storage/client.js +17 -0
  28. package/services/storage/client.js.map +1 -1
  29. package/services/storage/clients/profile.d.ts +76 -0
  30. package/services/storage/clients/profile.d.ts.map +1 -0
  31. package/services/storage/clients/profile.generated.d.ts +5 -0
  32. package/services/storage/clients/profile.generated.d.ts.map +1 -0
  33. package/services/storage/clients/profile.generated.js +162 -0
  34. package/services/storage/clients/profile.generated.js.map +1 -0
  35. package/services/storage/clients/profile.js +115 -0
  36. package/services/storage/clients/profile.js.map +1 -0
  37. package/services/storage/common.d.ts +16 -0
  38. package/services/storage/common.d.ts.map +1 -1
  39. package/services/storage/common.js.map +1 -1
package/lib/chaining.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as KeetaNet from "@keetanetwork/keetanet-client";
2
- import { convertAssetLocationToString, convertAssetSearchInputToCanonical, isChainLocation, toAssetLocation } from "../services/asset-movement/common.js";
2
+ import { convertAssetLocationToString, convertAssetSearchInputToCanonical, doesAssetOrPairMatch, isChainLocation, toAssetLocation } from "../services/asset-movement/common.js";
3
3
  import { getDefaultResolver } from '../config.js';
4
4
  import { Currency } from '@keetanetwork/currency-info';
5
5
  import { isAssetLocationLike } from '../services/asset-movement/lib/location.generated.js';
@@ -7,38 +7,14 @@ import { isFiatRail, isMovableAssetSearchCanonical, isRail } from '../services/a
7
7
  import { assertNever } from './utils/never.js';
8
8
  import KeetaFXAnchorClient from '../services/fx/client.js';
9
9
  import KeetaAssetMovementAnchorClient from '../services/asset-movement/client.js';
10
- import { isExternalChainAsset, normalizeChainAssetCasing } from './asset.js';
10
+ import { isExternalChainAsset, isMovableAssetEqual } from './asset.js';
11
11
  import { AnchorExternalBuilder } from './anchor-external.js';
12
12
  ;
13
13
  ;
14
14
  ;
15
15
  ;
16
- function areBothTokenAndEqual(a, b) {
17
- try {
18
- const aParsed = KeetaNet.lib.Account.toAccount(a);
19
- const bParsed = KeetaNet.lib.Account.toAccount(b);
20
- if (!aParsed.isToken() || !bParsed.isToken()) {
21
- return (false);
22
- }
23
- return (aParsed.comparePublicKey(bParsed));
24
- }
25
- catch {
26
- return (false);
27
- }
28
- }
29
16
  function isAnchorChainingAssetEqual(a, b) {
30
- // Compare string assets (currency codes, external-chain assets) with EVM
31
- // casing normalized, so the same token reported by two providers in
32
- // different EIP-55 casings is treated as equal.
33
- if (typeof a === 'string' && typeof b === 'string' && normalizeChainAssetCasing(a) === normalizeChainAssetCasing(b)) {
34
- return (true);
35
- }
36
- else if (areBothTokenAndEqual(a, b)) {
37
- return (true);
38
- }
39
- else {
40
- return (false);
41
- }
17
+ return (isMovableAssetEqual(a, b));
42
18
  }
43
19
  /**
44
20
  * Returns true for nodes that keep assets on Keeta: FX nodes, plus
@@ -55,6 +31,59 @@ function isFXLikeNode(node) {
55
31
  }
56
32
  export const DEFAULT_MAX_PATH_LENGTH = 5;
57
33
  export const DEFAULT_MAX_PATHS = 50;
34
+ const DEFAULT_FORWARDING_MAX_LEGS = 2;
35
+ const forwardingAssetKeyCache = new Map();
36
+ function forwardingAssetKey(asset, location) {
37
+ return (`${convertAssetSearchInputToCanonical(asset, forwardingAssetKeyCache)}@${convertAssetLocationToString(location)}`);
38
+ }
39
+ function isCryptoChainLocation(location) {
40
+ return (toAssetLocation(location).type === 'chain');
41
+ }
42
+ /**
43
+ * Adjacency over crypto persistent-forwarding edges only - excludes FX edges and
44
+ * any hop that starts on Keeta.
45
+ */
46
+ export function buildForwardingAdjacency(nodes) {
47
+ const adjacency = new Map();
48
+ for (const node of nodes) {
49
+ if (node.type !== 'assetMovement') {
50
+ continue;
51
+ }
52
+ if (node.from.supportedOperations?.createPersistentForwarding !== true) {
53
+ continue;
54
+ }
55
+ if (!isCryptoChainLocation(node.from.location) || !isCryptoChainLocation(node.to.location)) {
56
+ continue;
57
+ }
58
+ if (isChainLocation(toAssetLocation(node.from.location), 'keeta')) {
59
+ continue;
60
+ }
61
+ const key = forwardingAssetKey(node.from.asset, node.from.location);
62
+ const list = adjacency.get(key) ?? [];
63
+ list.push({ asset: node.to.asset, location: node.to.location });
64
+ adjacency.set(key, list);
65
+ }
66
+ return (adjacency);
67
+ }
68
+ /** Whether `dest` is reachable from `source` over <=`maxLegs` forwarding edges. */
69
+ export function hasForwardingRoute(adjacency, source, dest, maxLegs = DEFAULT_FORWARDING_MAX_LEGS) {
70
+ const destKey = forwardingAssetKey(dest.asset, dest.location);
71
+ let frontier = [forwardingAssetKey(source.asset, source.location)];
72
+ for (let depth = 0; depth < maxLegs; depth++) {
73
+ const next = [];
74
+ for (const key of frontier) {
75
+ for (const edge of adjacency.get(key) ?? []) {
76
+ const edgeKey = forwardingAssetKey(edge.asset, edge.location);
77
+ if (edgeKey === destKey) {
78
+ return (true);
79
+ }
80
+ next.push(edgeKey);
81
+ }
82
+ }
83
+ frontier = next;
84
+ }
85
+ return (false);
86
+ }
58
87
  class AnchorGraph {
59
88
  client;
60
89
  resolver;
@@ -66,6 +95,7 @@ class AnchorGraph {
66
95
  #evmChecksumCache = new Map();
67
96
  #graphNodePromise = null;
68
97
  #assetMovementProviderIdsByAssetLocation = null;
98
+ #resolveIndexPromise = null;
69
99
  constructor(args) {
70
100
  this.resolver = args.resolver;
71
101
  this.client = args.client;
@@ -153,48 +183,54 @@ class AnchorGraph {
153
183
  }
154
184
  const networkLocation = `chain:keeta:${this.client.network}`;
155
185
  const providerLookupResult = await Promise.all(Object.entries(fxServices).map(async ([providerID, service]) => {
156
- const fromEntries = await service.from('array');
157
- if (!fromEntries) {
158
- return (null);
159
- }
160
- const operations = await service.operations('object');
161
- if (!operations.createExchange) {
162
- this.logger?.debug('AnchorGraph::computeFXNodes', `FX service ${providerID} does not support createExchange operation, skipping`);
163
- return (null);
164
- }
165
- const pathNodes = await Promise.all(fromEntries.map(async function (fromEntry) {
166
- const pathNodesResult = [];
167
- const parsedEntry = await fromEntry('object');
168
- const [fromCodes, toCodes] = await Promise.all([
169
- parsedEntry.currencyCodes('array'),
170
- parsedEntry.to('array')
171
- ]);
172
- for (const from of fromCodes) {
173
- const fromResolved = await from('string');
174
- if (!fromResolved) {
175
- continue;
176
- }
177
- const fromAccount = KeetaNet.lib.Account.fromPublicKeyString(fromResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
178
- for (const to of toCodes) {
179
- const toResolved = await to('string');
180
- if (!toResolved) {
186
+ try {
187
+ const fromEntries = await service.from('array');
188
+ if (!fromEntries) {
189
+ return (null);
190
+ }
191
+ const operations = await service.operations('object');
192
+ if (!operations.createExchange) {
193
+ this.logger?.debug('AnchorGraph::computeFXNodes', `FX service ${providerID} does not support createExchange operation, skipping`);
194
+ return (null);
195
+ }
196
+ const pathNodes = await Promise.all(fromEntries.map(async function (fromEntry) {
197
+ const pathNodesResult = [];
198
+ const parsedEntry = await fromEntry('object');
199
+ const [fromCodes, toCodes] = await Promise.all([
200
+ parsedEntry.currencyCodes('array'),
201
+ parsedEntry.to('array')
202
+ ]);
203
+ for (const from of fromCodes) {
204
+ const fromResolved = await from('string');
205
+ if (!fromResolved) {
181
206
  continue;
182
207
  }
183
- const toAccount = KeetaNet.lib.Account.fromPublicKeyString(toResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
184
- if (fromAccount.comparePublicKey(toAccount)) {
185
- continue;
208
+ const fromAccount = KeetaNet.lib.Account.fromPublicKeyString(fromResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
209
+ for (const to of toCodes) {
210
+ const toResolved = await to('string');
211
+ if (!toResolved) {
212
+ continue;
213
+ }
214
+ const toAccount = KeetaNet.lib.Account.fromPublicKeyString(toResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
215
+ if (fromAccount.comparePublicKey(toAccount)) {
216
+ continue;
217
+ }
218
+ pathNodesResult.push({
219
+ type: 'fx',
220
+ providerID: providerID,
221
+ from: { asset: fromAccount, location: networkLocation, rail: 'KEETA_SEND' },
222
+ to: { asset: toAccount, location: networkLocation, rail: 'KEETA_SEND' }
223
+ });
186
224
  }
187
- pathNodesResult.push({
188
- type: 'fx',
189
- providerID: providerID,
190
- from: { asset: fromAccount, location: networkLocation, rail: 'KEETA_SEND' },
191
- to: { asset: toAccount, location: networkLocation, rail: 'KEETA_SEND' }
192
- });
193
225
  }
194
- }
195
- return (pathNodesResult);
196
- }));
197
- return (pathNodes.flat());
226
+ return (pathNodesResult);
227
+ }));
228
+ return (pathNodes.flat());
229
+ }
230
+ catch (error) {
231
+ this.logger?.warn('AnchorGraph::computeFXNodes', `Failed to parse FX service metadata for provider ${providerID} -- ignoring:`, error);
232
+ return (null);
233
+ }
198
234
  }));
199
235
  return (providerLookupResult.flat().filter((node) => !!node));
200
236
  }
@@ -326,83 +362,89 @@ class AnchorGraph {
326
362
  return ([]);
327
363
  }
328
364
  const providerResults = await Promise.all(Object.entries(assetMovementServices).map(async ([providerID, service]) => {
329
- const supportedOperationsMetadata = await service.operations('object');
330
- const supportedAssetsEntries = await service.supportedAssets('array');
331
- if (!supportedAssetsEntries) {
332
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `No supported assets found for provider ${providerID}`);
333
- return (null);
334
- }
335
- const pathNodesResult = await Promise.all(supportedAssetsEntries.map(async (assetEntry) => {
336
- const parsedEntry = await assetEntry('object');
337
- const pathsResolved = await parsedEntry.paths('array');
338
- const pathPromises = await Promise.allSettled(pathsResolved.map(async (pathResolvedInput) => {
339
- const pathResolved = await pathResolvedInput('object');
340
- const pairResolved = await pathResolved.pair('array');
341
- const [fromResolved, toResolved] = await Promise.all([
342
- this.#computeAssetMovementPairSide(pairResolved[0]),
343
- this.#computeAssetMovementPairSide(pairResolved[1])
344
- ]);
345
- function getProviderSupportedOperationsForRail(railSpecific) {
346
- const retval = {
347
- createPersistentForwarding: supportedOperationsMetadata.createPersistentForwarding !== undefined,
348
- initiateTransfer: supportedOperationsMetadata.initiateTransfer !== undefined
349
- };
350
- if (railSpecific) {
351
- retval.createPersistentForwarding = railSpecific.createPersistentForwarding ?? false;
352
- retval.initiateTransfer = railSpecific.initiateTransfer ?? false;
353
- }
354
- return (retval);
355
- }
356
- const pathNodes = [];
357
- for (const [src, dest] of [
358
- [fromResolved, toResolved],
359
- [toResolved, fromResolved]
360
- ]) {
361
- for (const inboundRail of [...(src.rails.common ?? []), ...(src.rails.inbound ?? [])]) {
362
- /*
363
- * Drop edges whose source rail explicitly cannot
364
- * initiate a transfer and also cannot create a
365
- * persistent forwarding address.
366
- */
367
- const inboundSupportedOperations = getProviderSupportedOperationsForRail(inboundRail.supportedOperations);
368
- if (inboundSupportedOperations.initiateTransfer === false && inboundSupportedOperations.createPersistentForwarding === false) {
369
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `Skipping ${providerID} edge from ${convertAssetLocationToString(src.location)} via rail ${inboundRail.rail}: neither initiateTransfer nor createPersistentForwarding supported`);
370
- continue;
365
+ try {
366
+ const supportedOperationsMetadata = await service.operations('object');
367
+ const supportedAssetsEntries = await service.supportedAssets('array');
368
+ if (!supportedAssetsEntries) {
369
+ this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `No supported assets found for provider ${providerID}`);
370
+ return (null);
371
+ }
372
+ const pathNodesResult = await Promise.all(supportedAssetsEntries.map(async (assetEntry) => {
373
+ const parsedEntry = await assetEntry('object');
374
+ const pathsResolved = await parsedEntry.paths('array');
375
+ const pathPromises = await Promise.allSettled(pathsResolved.map(async (pathResolvedInput) => {
376
+ const pathResolved = await pathResolvedInput('object');
377
+ const pairResolved = await pathResolved.pair('array');
378
+ const [fromResolved, toResolved] = await Promise.all([
379
+ this.#computeAssetMovementPairSide(pairResolved[0]),
380
+ this.#computeAssetMovementPairSide(pairResolved[1])
381
+ ]);
382
+ function getProviderSupportedOperationsForRail(railSpecific) {
383
+ const retval = {
384
+ createPersistentForwarding: supportedOperationsMetadata.createPersistentForwarding !== undefined,
385
+ initiateTransfer: supportedOperationsMetadata.initiateTransfer !== undefined
386
+ };
387
+ if (railSpecific) {
388
+ retval.createPersistentForwarding = railSpecific.createPersistentForwarding ?? false;
389
+ retval.initiateTransfer = railSpecific.initiateTransfer ?? false;
371
390
  }
372
- for (const outboundRail of [...(dest.rails.common ?? []), ...(dest.rails.outbound ?? [])]) {
373
- pathNodes.push({
374
- type: 'assetMovement',
375
- providerID: providerID,
376
- from: {
377
- asset: src.id,
378
- location: src.location,
379
- rail: inboundRail.rail,
380
- supportedOperations: getProviderSupportedOperationsForRail(inboundRail.supportedOperations)
381
- },
382
- to: {
383
- asset: dest.id,
384
- location: dest.location,
385
- rail: outboundRail.rail,
386
- supportedOperations: getProviderSupportedOperationsForRail(outboundRail.supportedOperations)
387
- }
388
- });
391
+ return (retval);
392
+ }
393
+ const pathNodes = [];
394
+ for (const [src, dest] of [
395
+ [fromResolved, toResolved],
396
+ [toResolved, fromResolved]
397
+ ]) {
398
+ for (const inboundRail of [...(src.rails.common ?? []), ...(src.rails.inbound ?? [])]) {
399
+ /*
400
+ * Drop edges whose source rail explicitly cannot
401
+ * initiate a transfer and also cannot create a
402
+ * persistent forwarding address.
403
+ */
404
+ const inboundSupportedOperations = getProviderSupportedOperationsForRail(inboundRail.supportedOperations);
405
+ if (inboundSupportedOperations.initiateTransfer === false && inboundSupportedOperations.createPersistentForwarding === false) {
406
+ this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `Skipping ${providerID} edge from ${convertAssetLocationToString(src.location)} via rail ${inboundRail.rail}: neither initiateTransfer nor createPersistentForwarding supported`);
407
+ continue;
408
+ }
409
+ for (const outboundRail of [...(dest.rails.common ?? []), ...(dest.rails.outbound ?? [])]) {
410
+ pathNodes.push({
411
+ type: 'assetMovement',
412
+ providerID: providerID,
413
+ from: {
414
+ asset: src.id,
415
+ location: src.location,
416
+ rail: inboundRail.rail,
417
+ supportedOperations: getProviderSupportedOperationsForRail(inboundRail.supportedOperations)
418
+ },
419
+ to: {
420
+ asset: dest.id,
421
+ location: dest.location,
422
+ rail: outboundRail.rail,
423
+ supportedOperations: getProviderSupportedOperationsForRail(outboundRail.supportedOperations)
424
+ }
425
+ });
426
+ }
389
427
  }
390
428
  }
429
+ return (pathNodes);
430
+ }));
431
+ const allPaths = [];
432
+ for (const resolved of pathPromises) {
433
+ if (resolved.status === 'rejected') {
434
+ this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `error fetching nodes for provider ${providerID}:`, resolved.reason);
435
+ }
436
+ else {
437
+ allPaths.push(...resolved.value);
438
+ }
391
439
  }
392
- return (pathNodes);
440
+ return (allPaths);
393
441
  }));
394
- const allPaths = [];
395
- for (const resolved of pathPromises) {
396
- if (resolved.status === 'rejected') {
397
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `error fetching nodes for ... TODO`, resolved.reason);
398
- }
399
- else {
400
- allPaths.push(...resolved.value);
401
- }
402
- }
403
- return (allPaths);
404
- }));
405
- return (pathNodesResult.flat());
442
+ return (pathNodesResult.flat());
443
+ }
444
+ catch (error) {
445
+ this.logger?.warn('AnchorGraph::computeAssetMovementNodes', `Failed to parse asset movement service metadata for provider ${providerID} -- ignoring:`, error);
446
+ return (null);
447
+ }
406
448
  }));
407
449
  return (providerResults.flat().filter((node) => !!node));
408
450
  }
@@ -525,6 +567,60 @@ class AnchorGraph {
525
567
  }
526
568
  return (paths);
527
569
  }
570
+ async #getResolveIndex() {
571
+ if (this.#resolveIndexPromise === null) {
572
+ this.#resolveIndexPromise = (async () => {
573
+ const nodes = await this.computeGraphNodes();
574
+ const fromAssetKeys = nodes.map(node => this.#assetLocationKey(node.from));
575
+ const toAssetKeys = nodes.map(node => this.#assetLocationKey(node.to));
576
+ const fromKeys = nodes.map((node, i) => `${node.from.rail}:${fromAssetKeys[i]}`);
577
+ const toKeys = nodes.map((node, i) => `${node.to.rail}:${toAssetKeys[i]}`);
578
+ const nodesByFromKey = new Map();
579
+ const nodesByToKey = new Map();
580
+ const nodesByFromAssetKey = new Map();
581
+ const nodesByToAssetKey = new Map();
582
+ const railInfo = new Map();
583
+ const addToBucket = (map, key, index) => {
584
+ if (key === undefined) {
585
+ throw (new Error(`Invalid node index during resolve-index construction: ${index}`));
586
+ }
587
+ let bucket = map.get(key);
588
+ if (!bucket) {
589
+ bucket = [];
590
+ map.set(key, bucket);
591
+ }
592
+ bucket.push(index);
593
+ };
594
+ const addRail = (assetKey, side, railSide, index) => {
595
+ if (assetKey === undefined) {
596
+ throw (new Error(`Invalid node index during resolve-index construction: ${index}`));
597
+ }
598
+ let info = railInfo.get(assetKey);
599
+ if (!info) {
600
+ info = { asset: side.asset, location: side.location, inbound: new Set(), outbound: new Set() };
601
+ railInfo.set(assetKey, info);
602
+ }
603
+ info[railSide].add(side.rail);
604
+ };
605
+ for (let i = 0; i < nodes.length; i++) {
606
+ const node = nodes[i];
607
+ if (!node) {
608
+ throw (new Error(`Invalid node index during resolve-index construction: ${i}`));
609
+ }
610
+ addToBucket(nodesByFromKey, fromKeys[i], i);
611
+ addToBucket(nodesByToKey, toKeys[i], i);
612
+ addToBucket(nodesByFromAssetKey, fromAssetKeys[i], i);
613
+ addToBucket(nodesByToAssetKey, toAssetKeys[i], i);
614
+ // Match buildResultMap's node/side ordering (to side before from
615
+ // side) so the representative asset/location for a key is stable.
616
+ addRail(toAssetKeys[i], node.to, 'inbound', i);
617
+ addRail(fromAssetKeys[i], node.from, 'outbound', i);
618
+ }
619
+ return ({ nodes, fromAssetKeys, toAssetKeys, fromKeys, toKeys, nodesByFromKey, nodesByToKey, nodesByFromAssetKey, nodesByToAssetKey, railInfo });
620
+ })();
621
+ }
622
+ return (await this.#resolveIndexPromise);
623
+ }
528
624
  async resolveAssets(filter = {}) {
529
625
  const { from: fromFilterInput, to: toFilterInput, maxStepCount, onlyAllowFXLike } = filter;
530
626
  const keetaNetworkLocation = `chain:keeta:${this.client.network}`;
@@ -535,29 +631,11 @@ class AnchorGraph {
535
631
  const toFilter = (onlyAllowFXLike && toFilterInput !== undefined && toFilterInput.location === undefined)
536
632
  ? { ...toFilterInput, location: keetaNetworkLocation }
537
633
  : toFilterInput;
538
- const nodes = await this.computeGraphNodes();
539
- const fromAssetKeys = nodes.map(node => this.#assetLocationKey(node.from));
540
- const toAssetKeys = nodes.map(node => this.#assetLocationKey(node.to));
541
- let fromKeys;
542
- let toKeys;
543
- let nodesByFromKey;
544
- let nodesByToKey;
545
- const buildBuckets = (keys) => {
546
- const map = new Map();
547
- for (let j = 0; j < keys.length; j++) {
548
- const key = keys[j];
549
- if (key === undefined) {
550
- throw (new Error(`Invalid node index during bucket construction: ${j}`));
551
- }
552
- let bucket = map.get(key);
553
- if (!bucket) {
554
- bucket = [];
555
- map.set(key, bucket);
556
- }
557
- bucket.push(j);
558
- }
559
- return (map);
560
- };
634
+ // Graph-invariant structures (keys, adjacency buckets, per-asset rail
635
+ // aggregation) are built once and reused across every call, so a fan-out
636
+ // of many filtered resolveAssets/listAssets calls doesn't rebuild them n
637
+ // times.
638
+ const { nodes, fromAssetKeys, toAssetKeys, fromKeys, toKeys, nodesByFromKey, nodesByToKey, nodesByFromAssetKey, nodesByToAssetKey, railInfo } = await this.#getResolveIndex();
561
639
  const sideMatchesFilter = (side, f) => {
562
640
  if (f.location !== undefined && convertAssetLocationToString(side.location) !== convertAssetLocationToString(f.location)) {
563
641
  return (false);
@@ -570,6 +648,30 @@ class AnchorGraph {
570
648
  }
571
649
  return (true);
572
650
  };
651
+ // The start nodes for a traversal are those whose relevant side matches the
652
+ // filter. When the filter pins both asset and location (the common case) we
653
+ // look them up by key in O(matches); otherwise we fall back to scanning all
654
+ // nodes. The key path avoids running isAnchorChainingAssetEqual -- and thus
655
+ // keccak -- per node, which on a large graph dominates fan-out patterns.
656
+ const assetBucketsForSide = { from: nodesByFromAssetKey, to: nodesByToAssetKey };
657
+ const computeStartIndices = (f, side) => {
658
+ if (f.asset !== undefined && f.location !== undefined) {
659
+ const key = this.#assetLocationKey({ asset: f.asset, location: f.location });
660
+ const candidates = assetBucketsForSide[side].get(key) ?? [];
661
+ if (f.rail === undefined) {
662
+ return (candidates);
663
+ }
664
+ return (candidates.filter(i => nodes[i]?.[side].rail === f.rail));
665
+ }
666
+ const out = [];
667
+ for (let i = 0; i < nodes.length; i++) {
668
+ const node = nodes[i];
669
+ if (node && sideMatchesFilter(node[side], f)) {
670
+ out.push(i);
671
+ }
672
+ }
673
+ return (out);
674
+ };
573
675
  // Separate reachable sets and distance maps for backward (from) and forward (to) traversals.
574
676
  const fromReachable = new Set();
575
677
  const fromDistances = new Map();
@@ -586,21 +688,14 @@ class AnchorGraph {
586
688
  };
587
689
  const markFromReachable = makeMarkFn(fromReachable, fromDistances);
588
690
  const markToReachable = makeMarkFn(toReachable, toDistances);
589
- const bfs = (startCondition, direction, markFn) => {
691
+ const bfs = (startIndices, direction, markFn) => {
590
692
  const markKeys = direction === 'forward' ? toAssetKeys : fromAssetKeys;
591
693
  const stepKeys = direction === 'forward' ? toKeys : fromKeys;
592
694
  const neighborBuckets = direction === 'forward' ? nodesByFromKey : nodesByToKey;
593
- if (!stepKeys || !neighborBuckets) {
594
- throw (new Error(`BFS buckets not initialized for direction ${direction}`));
595
- }
596
695
  const nodeVisited = new Set();
597
696
  const queue = [];
598
- for (let i = 0; i < nodes.length; i++) {
599
- const node = nodes[i];
600
- if (!node) {
601
- throw (new Error(`Invalid node index during BFS initialization: ${i}`));
602
- }
603
- if (startCondition(node) && !nodeVisited.has(i)) {
697
+ for (const i of startIndices) {
698
+ if (!nodeVisited.has(i)) {
604
699
  nodeVisited.add(i);
605
700
  queue.push({ nodeIdx: i, depth: 1 });
606
701
  }
@@ -646,19 +741,11 @@ class AnchorGraph {
646
741
  }
647
742
  }
648
743
  };
649
- if (fromFilter || toFilter) {
650
- const railFromKeys = nodes.map((node, i) => `${node.from.rail}:${fromAssetKeys[i]}`);
651
- const railToKeys = nodes.map((node, i) => `${node.to.rail}:${toAssetKeys[i]}`);
652
- fromKeys = railFromKeys;
653
- toKeys = railToKeys;
654
- if (fromFilter) {
655
- nodesByFromKey = buildBuckets(railFromKeys);
656
- bfs(node => sideMatchesFilter(node.from, fromFilter), 'forward', markToReachable);
657
- }
658
- if (toFilter) {
659
- nodesByToKey = buildBuckets(railToKeys);
660
- bfs(node => sideMatchesFilter(node.to, toFilter), 'backward', markFromReachable);
661
- }
744
+ if (fromFilter) {
745
+ bfs(computeStartIndices(fromFilter, 'from'), 'forward', markToReachable);
746
+ }
747
+ if (toFilter) {
748
+ bfs(computeStartIndices(toFilter, 'to'), 'backward', markFromReachable);
662
749
  }
663
750
  if (!fromFilter && !toFilter) {
664
751
  for (let i = 0; i < nodes.length; i++) {
@@ -676,9 +763,29 @@ class AnchorGraph {
676
763
  }
677
764
  }
678
765
  }
679
- // Second pass: build result maps by collecting inbound/outbound rails for every reachable
680
- // (asset, location) pair from ALL graph nodes, not just those on the traversal path.
681
- const buildResultMap = (reachable, distances) => {
766
+ // Build result maps by collecting inbound/outbound rails for every reachable
767
+ // (asset, location) pair. The common path reads the precomputed per-asset
768
+ // rail aggregation (railInfo) and so is O(reachable). onlyAllowFXLike needs
769
+ // to exclude non-fx-like nodes' rails -- which railInfo doesn't distinguish
770
+ // -- so it falls back to the O(nodes) scan.
771
+ const buildResultMapFast = (reachable, distances) => {
772
+ const resultMap = new Map();
773
+ for (const key of reachable) {
774
+ const info = railInfo.get(key);
775
+ if (!info) {
776
+ continue;
777
+ }
778
+ const distanceValue = distances.get(key);
779
+ resultMap.set(key, {
780
+ asset: info.asset,
781
+ location: info.location,
782
+ rails: { inbound: [...info.inbound], outbound: [...info.outbound] },
783
+ distance: distanceValue !== undefined ? { pathLength: distanceValue } : null
784
+ });
785
+ }
786
+ return (resultMap);
787
+ };
788
+ const buildResultMapFXLike = (reachable, distances) => {
682
789
  const resultMap = new Map();
683
790
  const getOrCreate = (key, side) => {
684
791
  let resultObj = resultMap.get(key);
@@ -701,7 +808,7 @@ class AnchorGraph {
701
808
  if (!node || toKey === undefined || fromKey === undefined) {
702
809
  throw (new Error(`Invalid node index during result-map construction: ${i}`));
703
810
  }
704
- if (onlyAllowFXLike && !isFXLikeNode(node)) {
811
+ if (!isFXLikeNode(node)) {
705
812
  continue;
706
813
  }
707
814
  if (reachable.has(toKey)) {
@@ -719,6 +826,7 @@ class AnchorGraph {
719
826
  }
720
827
  return (resultMap);
721
828
  };
829
+ const buildResultMap = onlyAllowFXLike ? buildResultMapFXLike : buildResultMapFast;
722
830
  const fromResultMap = buildResultMap(fromReachable, fromDistances);
723
831
  const toResultMap = buildResultMap(toReachable, toDistances);
724
832
  // When onlyAllowFXLike, exclude the filter asset from the result set so that
@@ -813,6 +921,233 @@ class AnchorGraph {
813
921
  return (result.to);
814
922
  }
815
923
  }
924
+ async buildForwardingAdjacency() {
925
+ return (buildForwardingAdjacency(await this.computeGraphNodes()));
926
+ }
927
+ }
928
+ function normalizeForwardingOnlyOptions(forwardingOnly) {
929
+ if (!forwardingOnly) {
930
+ return (undefined);
931
+ }
932
+ if (forwardingOnly === true) {
933
+ return ({ maxLegs: DEFAULT_FORWARDING_MAX_LEGS });
934
+ }
935
+ return ({
936
+ maxLegs: DEFAULT_FORWARDING_MAX_LEGS,
937
+ ...forwardingOnly
938
+ });
939
+ }
940
+ function toComputePlanOptions(options, forwardingOpts) {
941
+ const overrides = options?.overrides;
942
+ const forwardingOnly = forwardingOpts !== undefined;
943
+ if (overrides === undefined && !forwardingOnly) {
944
+ return (undefined);
945
+ }
946
+ return ({
947
+ ...(overrides !== undefined ? { overrides } : {}),
948
+ ...(forwardingOnly ? { forwardingOnly: true } : {})
949
+ });
950
+ }
951
+ /**
952
+ * Whether a discovered path is eligible for forwarding-only plan resolution:
953
+ * crypto chain hops only, no Keeta-origin legs, no FX, within maxLegs.
954
+ */
955
+ export function isForwardingPath(path, options) {
956
+ const maxLegs = options?.maxLegs ?? DEFAULT_FORWARDING_MAX_LEGS;
957
+ const legs = path.path;
958
+ if (legs.length < 1 || legs.length > maxLegs) {
959
+ return (false);
960
+ }
961
+ return (legs.every((step) => {
962
+ if (step.type !== 'assetMovement') {
963
+ return (false);
964
+ }
965
+ if (!isCryptoChainLocation(step.from.location) || !isCryptoChainLocation(step.to.location)) {
966
+ return (false);
967
+ }
968
+ if (isChainLocation(toAssetLocation(step.from.location), 'keeta')) {
969
+ return (false);
970
+ }
971
+ return (step.from.supportedOperations?.createPersistentForwarding === true);
972
+ }));
973
+ }
974
+ function computeFeeTotalFromBreakdown(valueIn, fees) {
975
+ let feeFromLineItems = 0n;
976
+ for (const lineItem of fees.lineItems) {
977
+ if ('value' in lineItem && lineItem.value !== undefined && lineItem.value !== '') {
978
+ feeFromLineItems += BigInt(lineItem.value);
979
+ }
980
+ else if (lineItem.purpose === 'VALUE_VARIABLE' && lineItem.basisPoints !== undefined) {
981
+ feeFromLineItems += valueIn * BigInt(lineItem.basisPoints) / 10000n;
982
+ }
983
+ }
984
+ let feeTotal = feeFromLineItems;
985
+ if (fees.total !== undefined && fees.total !== '') {
986
+ feeTotal = BigInt(fees.total);
987
+ }
988
+ return (feeTotal);
989
+ }
990
+ function estimateValueOutFromPersistentForwardingFees(valueIn, fees) {
991
+ if (!fees) {
992
+ return (valueIn);
993
+ }
994
+ const valueOut = valueIn - computeFeeTotalFromBreakdown(valueIn, fees);
995
+ return (valueOut < 1n ? 1n : valueOut);
996
+ }
997
+ /** @internal Exported for unit tests. */
998
+ export function estimateForwardingValueOut(valueIn, fees) {
999
+ return (estimateValueOutFromPersistentForwardingFees(valueIn, fees));
1000
+ }
1001
+ /** List combined fees for a computed chaining plan. Keeta-send steps are omitted (treated as zero). */
1002
+ export function listChainingPlanFees(plan) {
1003
+ const lineItems = [];
1004
+ const defaultFeeAsset = (step) => {
1005
+ if (step.type === 'fx') {
1006
+ const token = step.result.isQuote ? step.result.quote.cost.token : step.result.estimate.expectedCost.token;
1007
+ return (token.publicKeyString.get());
1008
+ }
1009
+ if (KeetaNet.lib.Account.isInstance(step.step.from.asset)) {
1010
+ return (step.step.from.asset.publicKeyString.get());
1011
+ }
1012
+ return (step.step.from.asset);
1013
+ };
1014
+ for (let stepIndex = 0; stepIndex < plan.plan.steps.length; stepIndex++) {
1015
+ const step = plan.plan.steps[stepIndex];
1016
+ if (!step || step.type === 'keetaSend') {
1017
+ continue;
1018
+ }
1019
+ const appendBreakdown = (breakdown, source) => {
1020
+ const stepDefaultAsset = defaultFeeAsset(step);
1021
+ const metadata = { stepIndex, step, source };
1022
+ const startLength = lineItems.length;
1023
+ for (const item of breakdown.lineItems) {
1024
+ const asset = item.asset ?? stepDefaultAsset;
1025
+ const base = {
1026
+ purpose: item.purpose,
1027
+ asset,
1028
+ metadata,
1029
+ ...(item.details !== undefined ? { details: item.details } : {})
1030
+ };
1031
+ if ('value' in item && item.value !== undefined && item.value !== '') {
1032
+ lineItems.push({
1033
+ ...base,
1034
+ value: item.value,
1035
+ ...(item.purpose === 'VALUE_VARIABLE' && 'basisPoints' in item && item.basisPoints !== undefined ? { basisPoints: item.basisPoints } : {})
1036
+ });
1037
+ continue;
1038
+ }
1039
+ if (item.purpose === 'VALUE_VARIABLE' && 'basisPoints' in item && item.basisPoints !== undefined) {
1040
+ lineItems.push({
1041
+ ...base,
1042
+ basisPoints: item.basisPoints,
1043
+ value: (step.valueIn * BigInt(item.basisPoints) / 10000n).toString()
1044
+ });
1045
+ }
1046
+ }
1047
+ if (breakdown.total !== undefined && breakdown.total !== '') {
1048
+ const authoritativeTotal = computeFeeTotalFromBreakdown(step.valueIn, breakdown);
1049
+ let lineItemSum = 0n;
1050
+ for (let i = startLength; i < lineItems.length; i++) {
1051
+ const emitted = lineItems[i];
1052
+ if (emitted?.value !== undefined && emitted.value !== '') {
1053
+ lineItemSum += BigInt(emitted.value);
1054
+ }
1055
+ }
1056
+ if (authoritativeTotal > lineItemSum) {
1057
+ lineItems.push({
1058
+ purpose: 'OTHER',
1059
+ asset: stepDefaultAsset,
1060
+ value: (authoritativeTotal - lineItemSum).toString(),
1061
+ metadata
1062
+ });
1063
+ }
1064
+ else if (authoritativeTotal < lineItemSum) {
1065
+ lineItems.splice(startLength);
1066
+ lineItems.push({
1067
+ purpose: 'OTHER',
1068
+ asset: stepDefaultAsset,
1069
+ value: authoritativeTotal.toString(),
1070
+ metadata
1071
+ });
1072
+ }
1073
+ }
1074
+ };
1075
+ const appendAssetFee = (assetFee, source) => {
1076
+ if (typeof assetFee === 'string') {
1077
+ lineItems.push({
1078
+ purpose: 'OTHER',
1079
+ asset: defaultFeeAsset(step),
1080
+ value: assetFee,
1081
+ metadata: { stepIndex, step, source }
1082
+ });
1083
+ return;
1084
+ }
1085
+ appendBreakdown(assetFee, source);
1086
+ };
1087
+ if (step.type === 'fx') {
1088
+ if (step.result.isQuote) {
1089
+ lineItems.push({
1090
+ purpose: 'PROVIDER',
1091
+ asset: step.result.quote.cost.token.publicKeyString.get(),
1092
+ value: step.result.quote.cost.amount.toString(),
1093
+ metadata: { stepIndex, step, source: 'fxQuote' }
1094
+ });
1095
+ }
1096
+ else {
1097
+ lineItems.push({
1098
+ purpose: 'PROVIDER',
1099
+ asset: step.result.estimate.expectedCost.token.publicKeyString.get(),
1100
+ value: step.result.estimate.expectedCost.max.toString(),
1101
+ metadata: { stepIndex, step, source: 'fxEstimate' }
1102
+ });
1103
+ }
1104
+ continue;
1105
+ }
1106
+ if (step.type === 'assetMovement') {
1107
+ appendAssetFee(step.usingInstruction.assetFee, 'transferInstruction');
1108
+ continue;
1109
+ }
1110
+ if (step.simulatedTransfer) {
1111
+ const simulatedInstruction = step.simulatedTransfer.instructions.find((instr) => instr.type === step.step.from.rail);
1112
+ if (simulatedInstruction && 'assetFee' in simulatedInstruction) {
1113
+ appendAssetFee(simulatedInstruction.assetFee, 'simulatedTransfer');
1114
+ continue;
1115
+ }
1116
+ }
1117
+ if (step.persistentAddress.fees) {
1118
+ appendBreakdown(step.persistentAddress.fees, 'persistentAddress');
1119
+ continue;
1120
+ }
1121
+ if (step.valueIn > step.valueOut) {
1122
+ lineItems.push({
1123
+ purpose: 'OTHER',
1124
+ asset: defaultFeeAsset(step),
1125
+ value: (step.valueIn - step.valueOut).toString(),
1126
+ metadata: { stepIndex, step, source: 'persistentAddress' }
1127
+ });
1128
+ }
1129
+ }
1130
+ return ({ lineItems });
1131
+ }
1132
+ /**
1133
+ * Whether a resolved plan is anchor-to-anchor with no user intermediary steps.
1134
+ * The user may still fund the initial deposit address once.
1135
+ */
1136
+ export function isForwardingPlan(plan) {
1137
+ const steps = plan.plan.steps;
1138
+ if (steps.length === 0) {
1139
+ return (false);
1140
+ }
1141
+ return (steps.every((step) => step.type === 'forwarded'));
1142
+ }
1143
+ /** Deposit address for the first forwarding leg of a forwarding-only plan. */
1144
+ export function getForwardingDepositAddress(plan) {
1145
+ const firstStep = plan.plan.steps[0];
1146
+ if (!firstStep || firstStep.type !== 'forwarded') {
1147
+ return (null);
1148
+ }
1149
+ const address = firstStep.persistentAddress.address;
1150
+ return (typeof address === 'string' ? address : null);
816
1151
  }
817
1152
  export class AnchorChainingPath {
818
1153
  request;
@@ -913,6 +1248,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
913
1248
  }
914
1249
  return (this.#_plan);
915
1250
  }
1251
+ listFees() {
1252
+ return (listChainingPlanFees(this));
1253
+ }
916
1254
  async #computePlan() {
917
1255
  if (this.#_plan) {
918
1256
  throw (new Error(`Steps have already been computed`));
@@ -953,45 +1291,11 @@ export class AnchorChainingPlan extends AnchorChainingPath {
953
1291
  return (found);
954
1292
  };
955
1293
  const forwardedSteps = new Map();
956
- for (let scanIndex = 0; scanIndex < this.path.length; scanIndex++) {
1294
+ const forwardingOnly = this.#options?.forwardingOnly === true;
1295
+ const resolvePersistentForwardingForStep = async (scanIndex, destinationAddress) => {
957
1296
  const scanStep = this.path[scanIndex];
958
1297
  if (!scanStep || scanStep.type !== 'assetMovement') {
959
- continue;
960
- }
961
- /**
962
- * PFR is selected in two cases:
963
- * (a) the source rail explicitly cannot accept a managed transfer.
964
- * (b) the prior step is also an asset-movement step (AMP -> AMP
965
- * transition) and the source rail supports PFR.
966
- *
967
- * Persistent forwarding only applies to non-Keeta (external chain)
968
- * source rails: the model is that the prior step deposits into a chain
969
- * address the bridge observes and auto-forwards. A Keeta-source leg
970
- * (KEETA_SEND) is always a user-initiated send -- the prior step routes
971
- * its output back to the user, who then sends again -- so it is never
972
- * PFR, even when the provider advertises createPersistentForwarding at
973
- * the provider level (which its bare KEETA_SEND rails would otherwise
974
- * inherit). Treating an on-Keeta swap as PFR skips the required second
975
- * send.
976
- */
977
- const priorStep = scanIndex > 0 ? this.path[scanIndex - 1] : null;
978
- const isAmpToAmpTransition = priorStep?.type === 'assetMovement';
979
- const pfrSupported = scanStep.from.supportedOperations?.createPersistentForwarding === true;
980
- const initiateForbidden = scanStep.from.supportedOperations?.initiateTransfer === false;
981
- const sourceIsKeeta = isChainLocation(toAssetLocation(scanStep.from.location), 'keeta');
982
- const shouldUsePFR = !sourceIsKeeta && (initiateForbidden || (isAmpToAmpTransition && pfrSupported));
983
- if (!shouldUsePFR) {
984
- continue;
985
- }
986
- if (!pfrSupported) {
987
- throw (new Error(`Asset movement provider ${scanStep.providerID} source rail ${scanStep.from.rail} at ${convertAssetLocationToString(scanStep.from.location)} declares initiateTransfer:false but does not support createPersistentForwarding`));
988
- }
989
- if (scanIndex !== this.path.length - 1) {
990
- throw (new Error(`Persistent-forwarding (PersistentForwardingRelay-only) asset movement steps are currently only supported as the last step in a chain (step ${scanIndex} of ${this.path.length})`));
991
- }
992
- const destinationAddress = this.request.destination.recipient;
993
- if (typeof destinationAddress !== 'string') {
994
- throw (new Error(`Persistent-forwarding step at index ${scanIndex} requires the chain's destination recipient to be a resolved address string`));
1298
+ throw (new Error(`Expected asset movement step at index ${scanIndex} for persistent forwarding`));
995
1299
  }
996
1300
  const forwardedAssetPair = { from: scanStep.from.asset, to: scanStep.to.asset };
997
1301
  const forwardedProviders = await assetMovementClient.getProvidersForTransfer({ asset: forwardedAssetPair, from: scanStep.from.location, to: scanStep.to.location }, { providerIDs: [scanStep.providerID] });
@@ -1002,7 +1306,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1002
1306
  if (!await forwardedProvider.isOperationSupported('createPersistentForwarding')) {
1003
1307
  throw (new Error(`Asset movement provider ${scanStep.providerID} does not support createPersistentForwarding, but the source rail ${scanStep.from.rail} at ${convertAssetLocationToString(scanStep.from.location)} requires it (initiateTransfer is unsupported)`));
1004
1308
  }
1005
- if (!await forwardedProvider.isOperationSupported('simulateTransfer')) {
1309
+ if (!forwardingOnly && !await forwardedProvider.isOperationSupported('simulateTransfer')) {
1006
1310
  throw (new Error(`Asset movement provider ${scanStep.providerID} does not support simulateTransfer, which is required to compute valueOut for a persistent-forwarding step at ${convertAssetLocationToString(scanStep.from.location)}`));
1007
1311
  }
1008
1312
  const { signer: forwardedSigner } = await this.getAccountsForAction({
@@ -1018,13 +1322,10 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1018
1322
  search: [{
1019
1323
  sourceLocation: scanStep.from.location,
1020
1324
  destinationLocation: scanStep.to.location,
1021
- asset: scanStep.from.asset,
1325
+ asset: forwardedAssetPair,
1022
1326
  destinationAddress
1023
1327
  }]
1024
1328
  });
1025
- /*
1026
- * Filter to the exact address this step requires.
1027
- */
1028
1329
  const sourceLocationString = convertAssetLocationToString(scanStep.from.location);
1029
1330
  const destLocationString = convertAssetLocationToString(scanStep.to.location);
1030
1331
  const match = existing.addresses.find(addr => {
@@ -1037,6 +1338,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1037
1338
  if (!addr.destinationLocation || convertAssetLocationToString(addr.destinationLocation) !== destLocationString) {
1038
1339
  return (false);
1039
1340
  }
1341
+ if (addr.asset && !doesAssetOrPairMatch(addr.asset, forwardedAssetPair)) {
1342
+ return (false);
1343
+ }
1040
1344
  return (true);
1041
1345
  });
1042
1346
  if (match) {
@@ -1060,6 +1364,84 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1060
1364
  throw (new Error(`Persistent forwarding address for step ${scanIndex} is not a resolved string (got ${typeof persistentAddress.address})`));
1061
1365
  }
1062
1366
  forwardedSteps.set(scanIndex, { provider: forwardedProvider, persistentAddress });
1367
+ };
1368
+ if (forwardingOnly) {
1369
+ for (let scanIndex = this.path.length - 1; scanIndex >= 0; scanIndex--) {
1370
+ const scanStep = this.path[scanIndex];
1371
+ if (!scanStep || scanStep.type !== 'assetMovement') {
1372
+ continue;
1373
+ }
1374
+ const pfrSupported = scanStep.from.supportedOperations?.createPersistentForwarding === true;
1375
+ const sourceIsKeeta = isChainLocation(toAssetLocation(scanStep.from.location), 'keeta');
1376
+ if (sourceIsKeeta || !pfrSupported) {
1377
+ throw (new Error(`Forwarding-only plan requires persistent forwarding support on every leg, but step ${scanIndex} at ${convertAssetLocationToString(scanStep.from.location)} does not qualify`));
1378
+ }
1379
+ let destinationAddress;
1380
+ if (scanIndex === this.path.length - 1) {
1381
+ const finalRecipient = this.request.destination.recipient;
1382
+ if (typeof finalRecipient !== 'string') {
1383
+ throw (new Error(`Forwarding-only plan requires the destination recipient to be a resolved address string`));
1384
+ }
1385
+ destinationAddress = finalRecipient;
1386
+ }
1387
+ else {
1388
+ const nextForwarded = forwardedSteps.get(scanIndex + 1);
1389
+ if (!nextForwarded) {
1390
+ throw (new Error(`Forwarding-only plan expected persistent forwarding to be resolved for next step ${scanIndex + 1}`));
1391
+ }
1392
+ const nextAddress = nextForwarded.persistentAddress.address;
1393
+ if (typeof nextAddress !== 'string') {
1394
+ throw (new Error(`Forwarding-only plan requires the next step persistent forwarding address to be a resolved string at index ${scanIndex + 1}`));
1395
+ }
1396
+ destinationAddress = nextAddress;
1397
+ }
1398
+ await resolvePersistentForwardingForStep(scanIndex, destinationAddress);
1399
+ }
1400
+ }
1401
+ for (let scanIndex = 0; scanIndex < this.path.length; scanIndex++) {
1402
+ if (forwardingOnly) {
1403
+ continue;
1404
+ }
1405
+ const scanStep = this.path[scanIndex];
1406
+ if (!scanStep || scanStep.type !== 'assetMovement') {
1407
+ continue;
1408
+ }
1409
+ /**
1410
+ * PFR is selected in two cases:
1411
+ * (a) the source rail explicitly cannot accept a managed transfer.
1412
+ * (b) the prior step is also an asset-movement step (AMP -> AMP
1413
+ * transition) and the source rail supports PFR.
1414
+ *
1415
+ * Persistent forwarding only applies to non-Keeta (external chain)
1416
+ * source rails: the model is that the prior step deposits into a chain
1417
+ * address the bridge observes and auto-forwards. A Keeta-source leg
1418
+ * (KEETA_SEND) is always a user-initiated send -- the prior step routes
1419
+ * its output back to the user, who then sends again -- so it is never
1420
+ * PFR, even when the provider advertises createPersistentForwarding at
1421
+ * the provider level (which its bare KEETA_SEND rails would otherwise
1422
+ * inherit). Treating an on-Keeta swap as PFR skips the required second
1423
+ * send.
1424
+ */
1425
+ const priorStep = scanIndex > 0 ? this.path[scanIndex - 1] : null;
1426
+ const isAmpToAmpTransition = priorStep?.type === 'assetMovement';
1427
+ const pfrSupported = scanStep.from.supportedOperations?.createPersistentForwarding === true;
1428
+ const initiateForbidden = scanStep.from.supportedOperations?.initiateTransfer === false;
1429
+ const sourceIsKeeta = isChainLocation(toAssetLocation(scanStep.from.location), 'keeta');
1430
+ const shouldUsePFR = !sourceIsKeeta && (initiateForbidden || (isAmpToAmpTransition && pfrSupported));
1431
+ if (!shouldUsePFR) {
1432
+ continue;
1433
+ }
1434
+ if (!pfrSupported) {
1435
+ throw (new Error(`Asset movement provider ${scanStep.providerID} source rail ${scanStep.from.rail} at ${convertAssetLocationToString(scanStep.from.location)} declares initiateTransfer:false but does not support createPersistentForwarding`));
1436
+ }
1437
+ if (scanIndex !== this.path.length - 1) {
1438
+ throw (new Error(`Persistent-forwarding (PersistentForwardingRelay-only) asset movement steps are currently only supported as the last step in a chain (step ${scanIndex} of ${this.path.length})`));
1439
+ }
1440
+ const destinationAddress = this.request.destination.recipient;
1441
+ if (typeof destinationAddress !== 'string') {
1442
+ throw (new Error(`Persistent-forwarding step at index ${scanIndex} requires the chain's destination recipient to be a resolved address string`));
1443
+ }
1444
+ await resolvePersistentForwardingForStep(scanIndex, destinationAddress);
1063
1445
  }
1064
1446
  const stepPromises = [];
1065
1447
  const resolvingSteps = new Set();
@@ -1156,26 +1538,26 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1156
1538
  const forwardedInfo = forwardedSteps.get(index);
1157
1539
  if (forwardedInfo) {
1158
1540
  const { provider: forwardedProvider, persistentAddress } = forwardedInfo;
1159
- /*
1160
- * Best-effort plan-time valueOut: simulateTransfer if available,
1161
- * otherwise assume no rail fee.
1162
- */
1163
1541
  let estimatedValueOut = depositValue;
1164
- if (await forwardedProvider.isOperationSupported('simulateTransfer')) {
1542
+ let simulatedTransfer;
1543
+ if (forwardingOnly) {
1544
+ estimatedValueOut = estimateValueOutFromPersistentForwardingFees(depositValue, persistentAddress.fees);
1545
+ }
1546
+ else if (await forwardedProvider.isOperationSupported('simulateTransfer')) {
1165
1547
  try {
1166
1548
  const { signer: forwardedSigner } = await this.getAccountsForAction({
1167
1549
  type: 'assetMovement',
1168
1550
  providerMethod: 'initiateTransfer',
1169
1551
  provider: forwardedProvider
1170
1552
  }, this.#options?.overrides);
1171
- const simulated = await forwardedProvider.simulateTransfer({
1553
+ simulatedTransfer = await forwardedProvider.simulateTransfer({
1172
1554
  account: forwardedSigner,
1173
1555
  asset: assetPair,
1174
1556
  from: { location: step.from.location },
1175
1557
  to: { location: step.to.location },
1176
1558
  value: depositValue
1177
1559
  });
1178
- const simulatedInstruction = simulated.instructions.find((instr) => instr.type === step.from.rail);
1560
+ const simulatedInstruction = simulatedTransfer.instructions.find((instr) => instr.type === step.from.rail);
1179
1561
  let simulatedTotalReceive;
1180
1562
  if (simulatedInstruction) {
1181
1563
  simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
@@ -1197,9 +1579,13 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1197
1579
  valueIn: depositValue,
1198
1580
  valueOut: estimatedValueOut,
1199
1581
  persistentAddress,
1200
- provider: forwardedProvider
1582
+ provider: forwardedProvider,
1583
+ ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1201
1584
  });
1202
1585
  }
1586
+ if (this.#options?.forwardingOnly) {
1587
+ throw (new Error(`Forwarding-only plan requires persistent forwarding for step at index ${index}, but none was resolved`));
1588
+ }
1203
1589
  const providers = await assetMovementClient.getProvidersForTransfer({ asset: assetPair, from: step.from.location, to: step.to.location }, { providerIDs: [step.providerID] });
1204
1590
  if (!providers?.[0] || providers.length === 0) {
1205
1591
  throw (new Error(`Could not get asset movement provider ${step.providerID}`));
@@ -1553,7 +1939,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1553
1939
  const external = await builder.build();
1554
1940
  return (external);
1555
1941
  }
1556
- async #pollTransferStatus(transfer, options) {
1942
+ async #pollTransferStatus(transfer, context, options) {
1557
1943
  const intervalMs = options?.intervalMs ?? 2000;
1558
1944
  const timeoutMs = options?.timeoutMs ?? 300_000;
1559
1945
  const deadline = Date.now() + timeoutMs;
@@ -1562,6 +1948,12 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1562
1948
  throw (new Error(`Aborted while waiting for transfer ${transfer.transferID} to complete`));
1563
1949
  }
1564
1950
  const status = await transfer.getTransferStatus();
1951
+ this.#emit('transactionObserved', {
1952
+ stepIndex: context.stepIndex,
1953
+ planStep: context.planStep,
1954
+ transaction: status.transaction,
1955
+ source: 'getTransferStatus'
1956
+ });
1565
1957
  if (status.transaction.status === 'COMPLETE') {
1566
1958
  return (status);
1567
1959
  }
@@ -1575,7 +1967,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1575
1967
  * Wait for the forwarded transfer the bridge creates after observing the
1576
1968
  * prior step's withdraw deposit in the persistent-forwarding address.
1577
1969
  */
1578
- async #pollForwardedTransaction(step, sourceTransaction, options) {
1970
+ async #pollForwardedTransaction(step, sourceTransaction, context, options) {
1579
1971
  const intervalMs = options?.intervalMs ?? 2000;
1580
1972
  const timeoutMs = options?.timeoutMs ?? 300_000;
1581
1973
  const deadline = Date.now() + timeoutMs;
@@ -1608,6 +2000,14 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1608
2000
  catch (error) {
1609
2001
  this.logger?.debug('AnchorChainingPlan::pollForwardedTransaction', `listTransactions failed for PersistentForwardingRelay address ${pfiAddress}`, error);
1610
2002
  }
2003
+ for (const transaction of transactions) {
2004
+ this.#emit('transactionObserved', {
2005
+ stepIndex: context.stepIndex,
2006
+ planStep: context.planStep,
2007
+ transaction,
2008
+ source: 'listTransactions'
2009
+ });
2010
+ }
1611
2011
  const candidate = transactions.find(tx => tx.status === 'COMPLETE');
1612
2012
  if (candidate) {
1613
2013
  return (candidate);
@@ -1640,6 +2040,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1640
2040
  }
1641
2041
  }
1642
2042
  async execute(options) {
2043
+ if (this.#options?.forwardingOnly) {
2044
+ throw (new Error('Forwarding-only plans cannot be executed. Use getPlans({ forwardingOnly: true }), which returns AnchorChainingForwardingOnlyPlan, and fund the deposit address externally.'));
2045
+ }
1643
2046
  if (this.#state.status !== 'idle') {
1644
2047
  throw (new Error(`Cannot execute: path is already in state "${this.#state.status}"`));
1645
2048
  }
@@ -1677,6 +2080,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1677
2080
  if (!step) {
1678
2081
  throw (new Error(`Step ${index} is not defined`));
1679
2082
  }
2083
+ const pollContext = { stepIndex: index, planStep: step };
1680
2084
  // Verify the actual output from the previous step matches the expected
1681
2085
  // input for this step. A mismatch indicates a provider delivered a
1682
2086
  // different amount than was negotiated in computeSteps.
@@ -1702,7 +2106,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1702
2106
  if (!prevWithdrawTx) {
1703
2107
  throw (new Error(`Forwarded step at index ${index} requires the prior step to produce a withdraw transaction on its destination chain`));
1704
2108
  }
1705
- const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, {
2109
+ const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, pollContext, {
1706
2110
  ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
1707
2111
  });
1708
2112
  prevActualValueOut = BigInt(observed.to.value);
@@ -1744,7 +2148,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1744
2148
  throw (new Error(`Unsupported instruction type ${step.usingInstruction.type} for user-initiated transfer at step ${index}`));
1745
2149
  }
1746
2150
  if (step.type === 'assetMovement') {
1747
- const status = await this.#pollTransferStatus(step.transfer, {
2151
+ const status = await this.#pollTransferStatus(step.transfer, pollContext, {
1748
2152
  ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
1749
2153
  });
1750
2154
  prevActualValueOut = BigInt(status.transaction.to.value);
@@ -1807,6 +2211,34 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1807
2211
  return (result);
1808
2212
  }
1809
2213
  }
2214
+ /**
2215
+ * Forwarding-only chaining plan for persistent-forwarding routes. Resolves deposit
2216
+ * addresses and fee estimates but cannot be executed: the user funds the
2217
+ * external deposit address directly.
2218
+ */
2219
+ export class AnchorChainingForwardingOnlyPlan extends AnchorChainingPath {
2220
+ #plan;
2221
+ constructor(path, plan) {
2222
+ super({ request: path.request, path: path.path, parent: path.parent });
2223
+ this.#plan = plan;
2224
+ }
2225
+ get plan() {
2226
+ return (this.#plan);
2227
+ }
2228
+ getDepositAddress() {
2229
+ return (getForwardingDepositAddress(this));
2230
+ }
2231
+ listFees() {
2232
+ return (listChainingPlanFees(this));
2233
+ }
2234
+ static async create(path, options) {
2235
+ const computed = await AnchorChainingPlan.create(path, { ...options, forwardingOnly: true });
2236
+ if (!isForwardingPlan(computed)) {
2237
+ throw (new Error('Computed plan does not qualify as a forwarding-only route'));
2238
+ }
2239
+ return (new AnchorChainingForwardingOnlyPlan(path, computed.plan));
2240
+ }
2241
+ }
1810
2242
  export class AnchorChaining {
1811
2243
  client;
1812
2244
  resolver;
@@ -1872,10 +2304,17 @@ export class AnchorChaining {
1872
2304
  return (retval);
1873
2305
  }
1874
2306
  async getPlans(input, options) {
1875
- const paths = await this.getPaths(input);
2307
+ const forwardingOpts = normalizeForwardingOnlyOptions(options?.forwardingOnly);
2308
+ let paths = await this.getPaths(input);
1876
2309
  if (!paths) {
1877
2310
  return (null);
1878
2311
  }
2312
+ if (forwardingOpts) {
2313
+ paths = paths.filter((path) => isForwardingPath(path, forwardingOpts));
2314
+ if (paths.length === 0) {
2315
+ return (null);
2316
+ }
2317
+ }
1879
2318
  const limit = options?.limit ?? 3;
1880
2319
  const sortedPaths = paths.sort((a, b) => a.path.length - b.path.length);
1881
2320
  let successCount = 0;
@@ -1894,7 +2333,11 @@ export class AnchorChaining {
1894
2333
  break;
1895
2334
  }
1896
2335
  const currentTry = await Promise.allSettled(pathsToTry.map(async function (path) {
1897
- return (await AnchorChainingPlan.create(path, options));
2336
+ const computeOptions = toComputePlanOptions(options, forwardingOpts);
2337
+ if (forwardingOpts) {
2338
+ return (await AnchorChainingForwardingOnlyPlan.create(path, computeOptions));
2339
+ }
2340
+ return (await AnchorChainingPlan.create(path, computeOptions));
1898
2341
  }));
1899
2342
  allOutput.push(...currentTry);
1900
2343
  for (let i = 0; i < currentTry.length; i++) {
@@ -1904,9 +2347,12 @@ export class AnchorChaining {
1904
2347
  continue;
1905
2348
  }
1906
2349
  if (result.status === 'fulfilled') {
1907
- successCount++;
1908
- if (path && path.path.length < lowestStepsSuccessCount) {
1909
- lowestStepsSuccessCount = path.path.length;
2350
+ const qualifies = !forwardingOpts || isForwardingPlan(result.value);
2351
+ if (qualifies) {
2352
+ successCount++;
2353
+ if (path && path.path.length < lowestStepsSuccessCount) {
2354
+ lowestStepsSuccessCount = path.path.length;
2355
+ }
1910
2356
  }
1911
2357
  }
1912
2358
  }
@@ -1923,7 +2369,13 @@ export class AnchorChaining {
1923
2369
  if (plan.status === 'rejected') {
1924
2370
  ret.push({ success: false, error: plan.reason, path });
1925
2371
  }
1926
- else {
2372
+ else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2373
+ ret.push({ success: false, error: new Error('Plan does not qualify as a forwarding-only route'), path });
2374
+ }
2375
+ else if (plan.value instanceof AnchorChainingForwardingOnlyPlan) {
2376
+ ret.push({ success: true, plan: plan.value, path });
2377
+ }
2378
+ else if (plan.value instanceof AnchorChainingPlan) {
1927
2379
  ret.push({ success: true, plan: plan.value, path });
1928
2380
  }
1929
2381
  }
@@ -1931,11 +2383,17 @@ export class AnchorChaining {
1931
2383
  if (plan.status === 'rejected') {
1932
2384
  this.logger?.debug(`AnchorChaining::getPlans`, `Error computing plan for a path:`, plan.reason);
1933
2385
  }
2386
+ else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2387
+ this.logger?.debug(`AnchorChaining::getPlans`, `Skipping plan that does not qualify as forwarding-only`);
2388
+ }
1934
2389
  else {
1935
2390
  ret.push(plan.value);
1936
2391
  }
1937
2392
  }
1938
2393
  }
2394
+ if (forwardingOpts && !options?.includeAllOutput && ret.length === 0) {
2395
+ return (null);
2396
+ }
1939
2397
  return (ret);
1940
2398
  }
1941
2399
  }