@keetanetwork/anchor 0.0.86 → 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.
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;
@@ -154,48 +183,54 @@ class AnchorGraph {
154
183
  }
155
184
  const networkLocation = `chain:keeta:${this.client.network}`;
156
185
  const providerLookupResult = await Promise.all(Object.entries(fxServices).map(async ([providerID, service]) => {
157
- const fromEntries = await service.from('array');
158
- if (!fromEntries) {
159
- return (null);
160
- }
161
- const operations = await service.operations('object');
162
- if (!operations.createExchange) {
163
- this.logger?.debug('AnchorGraph::computeFXNodes', `FX service ${providerID} does not support createExchange operation, skipping`);
164
- return (null);
165
- }
166
- const pathNodes = await Promise.all(fromEntries.map(async function (fromEntry) {
167
- const pathNodesResult = [];
168
- const parsedEntry = await fromEntry('object');
169
- const [fromCodes, toCodes] = await Promise.all([
170
- parsedEntry.currencyCodes('array'),
171
- parsedEntry.to('array')
172
- ]);
173
- for (const from of fromCodes) {
174
- const fromResolved = await from('string');
175
- if (!fromResolved) {
176
- continue;
177
- }
178
- const fromAccount = KeetaNet.lib.Account.fromPublicKeyString(fromResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
179
- for (const to of toCodes) {
180
- const toResolved = await to('string');
181
- 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) {
182
206
  continue;
183
207
  }
184
- const toAccount = KeetaNet.lib.Account.fromPublicKeyString(toResolved).assertKeyType(KeetaNet.lib.Account.AccountKeyAlgorithm.TOKEN);
185
- if (fromAccount.comparePublicKey(toAccount)) {
186
- 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
+ });
187
224
  }
188
- pathNodesResult.push({
189
- type: 'fx',
190
- providerID: providerID,
191
- from: { asset: fromAccount, location: networkLocation, rail: 'KEETA_SEND' },
192
- to: { asset: toAccount, location: networkLocation, rail: 'KEETA_SEND' }
193
- });
194
225
  }
195
- }
196
- return (pathNodesResult);
197
- }));
198
- 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
+ }
199
234
  }));
200
235
  return (providerLookupResult.flat().filter((node) => !!node));
201
236
  }
@@ -327,83 +362,89 @@ class AnchorGraph {
327
362
  return ([]);
328
363
  }
329
364
  const providerResults = await Promise.all(Object.entries(assetMovementServices).map(async ([providerID, service]) => {
330
- const supportedOperationsMetadata = await service.operations('object');
331
- const supportedAssetsEntries = await service.supportedAssets('array');
332
- if (!supportedAssetsEntries) {
333
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `No supported assets found for provider ${providerID}`);
334
- return (null);
335
- }
336
- const pathNodesResult = await Promise.all(supportedAssetsEntries.map(async (assetEntry) => {
337
- const parsedEntry = await assetEntry('object');
338
- const pathsResolved = await parsedEntry.paths('array');
339
- const pathPromises = await Promise.allSettled(pathsResolved.map(async (pathResolvedInput) => {
340
- const pathResolved = await pathResolvedInput('object');
341
- const pairResolved = await pathResolved.pair('array');
342
- const [fromResolved, toResolved] = await Promise.all([
343
- this.#computeAssetMovementPairSide(pairResolved[0]),
344
- this.#computeAssetMovementPairSide(pairResolved[1])
345
- ]);
346
- function getProviderSupportedOperationsForRail(railSpecific) {
347
- const retval = {
348
- createPersistentForwarding: supportedOperationsMetadata.createPersistentForwarding !== undefined,
349
- initiateTransfer: supportedOperationsMetadata.initiateTransfer !== undefined
350
- };
351
- if (railSpecific) {
352
- retval.createPersistentForwarding = railSpecific.createPersistentForwarding ?? false;
353
- retval.initiateTransfer = railSpecific.initiateTransfer ?? false;
354
- }
355
- return (retval);
356
- }
357
- const pathNodes = [];
358
- for (const [src, dest] of [
359
- [fromResolved, toResolved],
360
- [toResolved, fromResolved]
361
- ]) {
362
- for (const inboundRail of [...(src.rails.common ?? []), ...(src.rails.inbound ?? [])]) {
363
- /*
364
- * Drop edges whose source rail explicitly cannot
365
- * initiate a transfer and also cannot create a
366
- * persistent forwarding address.
367
- */
368
- const inboundSupportedOperations = getProviderSupportedOperationsForRail(inboundRail.supportedOperations);
369
- if (inboundSupportedOperations.initiateTransfer === false && inboundSupportedOperations.createPersistentForwarding === false) {
370
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `Skipping ${providerID} edge from ${convertAssetLocationToString(src.location)} via rail ${inboundRail.rail}: neither initiateTransfer nor createPersistentForwarding supported`);
371
- 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;
372
390
  }
373
- for (const outboundRail of [...(dest.rails.common ?? []), ...(dest.rails.outbound ?? [])]) {
374
- pathNodes.push({
375
- type: 'assetMovement',
376
- providerID: providerID,
377
- from: {
378
- asset: src.id,
379
- location: src.location,
380
- rail: inboundRail.rail,
381
- supportedOperations: getProviderSupportedOperationsForRail(inboundRail.supportedOperations)
382
- },
383
- to: {
384
- asset: dest.id,
385
- location: dest.location,
386
- rail: outboundRail.rail,
387
- supportedOperations: getProviderSupportedOperationsForRail(outboundRail.supportedOperations)
388
- }
389
- });
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
+ }
390
427
  }
391
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
+ }
392
439
  }
393
- return (pathNodes);
440
+ return (allPaths);
394
441
  }));
395
- const allPaths = [];
396
- for (const resolved of pathPromises) {
397
- if (resolved.status === 'rejected') {
398
- this.logger?.debug('AnchorGraph::computeAssetMovementNodes', `error fetching nodes for ... TODO`, resolved.reason);
399
- }
400
- else {
401
- allPaths.push(...resolved.value);
402
- }
403
- }
404
- return (allPaths);
405
- }));
406
- 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
+ }
407
448
  }));
408
449
  return (providerResults.flat().filter((node) => !!node));
409
450
  }
@@ -880,6 +921,233 @@ class AnchorGraph {
880
921
  return (result.to);
881
922
  }
882
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);
883
1151
  }
884
1152
  export class AnchorChainingPath {
885
1153
  request;
@@ -980,6 +1248,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
980
1248
  }
981
1249
  return (this.#_plan);
982
1250
  }
1251
+ listFees() {
1252
+ return (listChainingPlanFees(this));
1253
+ }
983
1254
  async #computePlan() {
984
1255
  if (this.#_plan) {
985
1256
  throw (new Error(`Steps have already been computed`));
@@ -1020,45 +1291,11 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1020
1291
  return (found);
1021
1292
  };
1022
1293
  const forwardedSteps = new Map();
1023
- for (let scanIndex = 0; scanIndex < this.path.length; scanIndex++) {
1294
+ const forwardingOnly = this.#options?.forwardingOnly === true;
1295
+ const resolvePersistentForwardingForStep = async (scanIndex, destinationAddress) => {
1024
1296
  const scanStep = this.path[scanIndex];
1025
1297
  if (!scanStep || scanStep.type !== 'assetMovement') {
1026
- continue;
1027
- }
1028
- /**
1029
- * PFR is selected in two cases:
1030
- * (a) the source rail explicitly cannot accept a managed transfer.
1031
- * (b) the prior step is also an asset-movement step (AMP -> AMP
1032
- * transition) and the source rail supports PFR.
1033
- *
1034
- * Persistent forwarding only applies to non-Keeta (external chain)
1035
- * source rails: the model is that the prior step deposits into a chain
1036
- * address the bridge observes and auto-forwards. A Keeta-source leg
1037
- * (KEETA_SEND) is always a user-initiated send -- the prior step routes
1038
- * its output back to the user, who then sends again -- so it is never
1039
- * PFR, even when the provider advertises createPersistentForwarding at
1040
- * the provider level (which its bare KEETA_SEND rails would otherwise
1041
- * inherit). Treating an on-Keeta swap as PFR skips the required second
1042
- * send.
1043
- */
1044
- const priorStep = scanIndex > 0 ? this.path[scanIndex - 1] : null;
1045
- const isAmpToAmpTransition = priorStep?.type === 'assetMovement';
1046
- const pfrSupported = scanStep.from.supportedOperations?.createPersistentForwarding === true;
1047
- const initiateForbidden = scanStep.from.supportedOperations?.initiateTransfer === false;
1048
- const sourceIsKeeta = isChainLocation(toAssetLocation(scanStep.from.location), 'keeta');
1049
- const shouldUsePFR = !sourceIsKeeta && (initiateForbidden || (isAmpToAmpTransition && pfrSupported));
1050
- if (!shouldUsePFR) {
1051
- continue;
1052
- }
1053
- if (!pfrSupported) {
1054
- 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`));
1055
- }
1056
- if (scanIndex !== this.path.length - 1) {
1057
- 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})`));
1058
- }
1059
- const destinationAddress = this.request.destination.recipient;
1060
- if (typeof destinationAddress !== 'string') {
1061
- 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`));
1062
1299
  }
1063
1300
  const forwardedAssetPair = { from: scanStep.from.asset, to: scanStep.to.asset };
1064
1301
  const forwardedProviders = await assetMovementClient.getProvidersForTransfer({ asset: forwardedAssetPair, from: scanStep.from.location, to: scanStep.to.location }, { providerIDs: [scanStep.providerID] });
@@ -1069,7 +1306,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1069
1306
  if (!await forwardedProvider.isOperationSupported('createPersistentForwarding')) {
1070
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)`));
1071
1308
  }
1072
- if (!await forwardedProvider.isOperationSupported('simulateTransfer')) {
1309
+ if (!forwardingOnly && !await forwardedProvider.isOperationSupported('simulateTransfer')) {
1073
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)}`));
1074
1311
  }
1075
1312
  const { signer: forwardedSigner } = await this.getAccountsForAction({
@@ -1085,13 +1322,10 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1085
1322
  search: [{
1086
1323
  sourceLocation: scanStep.from.location,
1087
1324
  destinationLocation: scanStep.to.location,
1088
- asset: scanStep.from.asset,
1325
+ asset: forwardedAssetPair,
1089
1326
  destinationAddress
1090
1327
  }]
1091
1328
  });
1092
- /*
1093
- * Filter to the exact address this step requires.
1094
- */
1095
1329
  const sourceLocationString = convertAssetLocationToString(scanStep.from.location);
1096
1330
  const destLocationString = convertAssetLocationToString(scanStep.to.location);
1097
1331
  const match = existing.addresses.find(addr => {
@@ -1104,6 +1338,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1104
1338
  if (!addr.destinationLocation || convertAssetLocationToString(addr.destinationLocation) !== destLocationString) {
1105
1339
  return (false);
1106
1340
  }
1341
+ if (addr.asset && !doesAssetOrPairMatch(addr.asset, forwardedAssetPair)) {
1342
+ return (false);
1343
+ }
1107
1344
  return (true);
1108
1345
  });
1109
1346
  if (match) {
@@ -1127,6 +1364,84 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1127
1364
  throw (new Error(`Persistent forwarding address for step ${scanIndex} is not a resolved string (got ${typeof persistentAddress.address})`));
1128
1365
  }
1129
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);
1130
1445
  }
1131
1446
  const stepPromises = [];
1132
1447
  const resolvingSteps = new Set();
@@ -1223,26 +1538,26 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1223
1538
  const forwardedInfo = forwardedSteps.get(index);
1224
1539
  if (forwardedInfo) {
1225
1540
  const { provider: forwardedProvider, persistentAddress } = forwardedInfo;
1226
- /*
1227
- * Best-effort plan-time valueOut: simulateTransfer if available,
1228
- * otherwise assume no rail fee.
1229
- */
1230
1541
  let estimatedValueOut = depositValue;
1231
- 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')) {
1232
1547
  try {
1233
1548
  const { signer: forwardedSigner } = await this.getAccountsForAction({
1234
1549
  type: 'assetMovement',
1235
1550
  providerMethod: 'initiateTransfer',
1236
1551
  provider: forwardedProvider
1237
1552
  }, this.#options?.overrides);
1238
- const simulated = await forwardedProvider.simulateTransfer({
1553
+ simulatedTransfer = await forwardedProvider.simulateTransfer({
1239
1554
  account: forwardedSigner,
1240
1555
  asset: assetPair,
1241
1556
  from: { location: step.from.location },
1242
1557
  to: { location: step.to.location },
1243
1558
  value: depositValue
1244
1559
  });
1245
- const simulatedInstruction = simulated.instructions.find((instr) => instr.type === step.from.rail);
1560
+ const simulatedInstruction = simulatedTransfer.instructions.find((instr) => instr.type === step.from.rail);
1246
1561
  let simulatedTotalReceive;
1247
1562
  if (simulatedInstruction) {
1248
1563
  simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
@@ -1264,9 +1579,13 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1264
1579
  valueIn: depositValue,
1265
1580
  valueOut: estimatedValueOut,
1266
1581
  persistentAddress,
1267
- provider: forwardedProvider
1582
+ provider: forwardedProvider,
1583
+ ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1268
1584
  });
1269
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
+ }
1270
1589
  const providers = await assetMovementClient.getProvidersForTransfer({ asset: assetPair, from: step.from.location, to: step.to.location }, { providerIDs: [step.providerID] });
1271
1590
  if (!providers?.[0] || providers.length === 0) {
1272
1591
  throw (new Error(`Could not get asset movement provider ${step.providerID}`));
@@ -1620,7 +1939,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1620
1939
  const external = await builder.build();
1621
1940
  return (external);
1622
1941
  }
1623
- async #pollTransferStatus(transfer, options) {
1942
+ async #pollTransferStatus(transfer, context, options) {
1624
1943
  const intervalMs = options?.intervalMs ?? 2000;
1625
1944
  const timeoutMs = options?.timeoutMs ?? 300_000;
1626
1945
  const deadline = Date.now() + timeoutMs;
@@ -1629,6 +1948,12 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1629
1948
  throw (new Error(`Aborted while waiting for transfer ${transfer.transferID} to complete`));
1630
1949
  }
1631
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
+ });
1632
1957
  if (status.transaction.status === 'COMPLETE') {
1633
1958
  return (status);
1634
1959
  }
@@ -1642,7 +1967,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1642
1967
  * Wait for the forwarded transfer the bridge creates after observing the
1643
1968
  * prior step's withdraw deposit in the persistent-forwarding address.
1644
1969
  */
1645
- async #pollForwardedTransaction(step, sourceTransaction, options) {
1970
+ async #pollForwardedTransaction(step, sourceTransaction, context, options) {
1646
1971
  const intervalMs = options?.intervalMs ?? 2000;
1647
1972
  const timeoutMs = options?.timeoutMs ?? 300_000;
1648
1973
  const deadline = Date.now() + timeoutMs;
@@ -1675,6 +2000,14 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1675
2000
  catch (error) {
1676
2001
  this.logger?.debug('AnchorChainingPlan::pollForwardedTransaction', `listTransactions failed for PersistentForwardingRelay address ${pfiAddress}`, error);
1677
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
+ }
1678
2011
  const candidate = transactions.find(tx => tx.status === 'COMPLETE');
1679
2012
  if (candidate) {
1680
2013
  return (candidate);
@@ -1707,6 +2040,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1707
2040
  }
1708
2041
  }
1709
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
+ }
1710
2046
  if (this.#state.status !== 'idle') {
1711
2047
  throw (new Error(`Cannot execute: path is already in state "${this.#state.status}"`));
1712
2048
  }
@@ -1744,6 +2080,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1744
2080
  if (!step) {
1745
2081
  throw (new Error(`Step ${index} is not defined`));
1746
2082
  }
2083
+ const pollContext = { stepIndex: index, planStep: step };
1747
2084
  // Verify the actual output from the previous step matches the expected
1748
2085
  // input for this step. A mismatch indicates a provider delivered a
1749
2086
  // different amount than was negotiated in computeSteps.
@@ -1769,7 +2106,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1769
2106
  if (!prevWithdrawTx) {
1770
2107
  throw (new Error(`Forwarded step at index ${index} requires the prior step to produce a withdraw transaction on its destination chain`));
1771
2108
  }
1772
- const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, {
2109
+ const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, pollContext, {
1773
2110
  ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
1774
2111
  });
1775
2112
  prevActualValueOut = BigInt(observed.to.value);
@@ -1811,7 +2148,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1811
2148
  throw (new Error(`Unsupported instruction type ${step.usingInstruction.type} for user-initiated transfer at step ${index}`));
1812
2149
  }
1813
2150
  if (step.type === 'assetMovement') {
1814
- const status = await this.#pollTransferStatus(step.transfer, {
2151
+ const status = await this.#pollTransferStatus(step.transfer, pollContext, {
1815
2152
  ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
1816
2153
  });
1817
2154
  prevActualValueOut = BigInt(status.transaction.to.value);
@@ -1874,6 +2211,34 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1874
2211
  return (result);
1875
2212
  }
1876
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
+ }
1877
2242
  export class AnchorChaining {
1878
2243
  client;
1879
2244
  resolver;
@@ -1939,10 +2304,17 @@ export class AnchorChaining {
1939
2304
  return (retval);
1940
2305
  }
1941
2306
  async getPlans(input, options) {
1942
- const paths = await this.getPaths(input);
2307
+ const forwardingOpts = normalizeForwardingOnlyOptions(options?.forwardingOnly);
2308
+ let paths = await this.getPaths(input);
1943
2309
  if (!paths) {
1944
2310
  return (null);
1945
2311
  }
2312
+ if (forwardingOpts) {
2313
+ paths = paths.filter((path) => isForwardingPath(path, forwardingOpts));
2314
+ if (paths.length === 0) {
2315
+ return (null);
2316
+ }
2317
+ }
1946
2318
  const limit = options?.limit ?? 3;
1947
2319
  const sortedPaths = paths.sort((a, b) => a.path.length - b.path.length);
1948
2320
  let successCount = 0;
@@ -1961,7 +2333,11 @@ export class AnchorChaining {
1961
2333
  break;
1962
2334
  }
1963
2335
  const currentTry = await Promise.allSettled(pathsToTry.map(async function (path) {
1964
- 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));
1965
2341
  }));
1966
2342
  allOutput.push(...currentTry);
1967
2343
  for (let i = 0; i < currentTry.length; i++) {
@@ -1971,9 +2347,12 @@ export class AnchorChaining {
1971
2347
  continue;
1972
2348
  }
1973
2349
  if (result.status === 'fulfilled') {
1974
- successCount++;
1975
- if (path && path.path.length < lowestStepsSuccessCount) {
1976
- 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
+ }
1977
2356
  }
1978
2357
  }
1979
2358
  }
@@ -1990,7 +2369,13 @@ export class AnchorChaining {
1990
2369
  if (plan.status === 'rejected') {
1991
2370
  ret.push({ success: false, error: plan.reason, path });
1992
2371
  }
1993
- 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) {
1994
2379
  ret.push({ success: true, plan: plan.value, path });
1995
2380
  }
1996
2381
  }
@@ -1998,11 +2383,17 @@ export class AnchorChaining {
1998
2383
  if (plan.status === 'rejected') {
1999
2384
  this.logger?.debug(`AnchorChaining::getPlans`, `Error computing plan for a path:`, plan.reason);
2000
2385
  }
2386
+ else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2387
+ this.logger?.debug(`AnchorChaining::getPlans`, `Skipping plan that does not qualify as forwarding-only`);
2388
+ }
2001
2389
  else {
2002
2390
  ret.push(plan.value);
2003
2391
  }
2004
2392
  }
2005
2393
  }
2394
+ if (forwardingOpts && !options?.includeAllOutput && ret.length === 0) {
2395
+ return (null);
2396
+ }
2006
2397
  return (ret);
2007
2398
  }
2008
2399
  }