@keetanetwork/anchor 0.0.95 → 0.0.97

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 (51) hide show
  1. package/lib/chaining.d.ts +33 -13
  2. package/lib/chaining.d.ts.map +1 -1
  3. package/lib/chaining.js +379 -304
  4. package/lib/chaining.js.map +1 -1
  5. package/lib/queue/drivers/queue_file.d.ts +1 -0
  6. package/lib/queue/drivers/queue_file.d.ts.map +1 -1
  7. package/lib/queue/drivers/queue_file.js +4 -0
  8. package/lib/queue/drivers/queue_file.js.map +1 -1
  9. package/lib/queue/drivers/queue_firestore.d.ts +2 -1
  10. package/lib/queue/drivers/queue_firestore.d.ts.map +1 -1
  11. package/lib/queue/drivers/queue_firestore.js +34 -0
  12. package/lib/queue/drivers/queue_firestore.js.map +1 -1
  13. package/lib/queue/drivers/queue_postgres.d.ts +2 -1
  14. package/lib/queue/drivers/queue_postgres.d.ts.map +1 -1
  15. package/lib/queue/drivers/queue_postgres.js +40 -6
  16. package/lib/queue/drivers/queue_postgres.js.map +1 -1
  17. package/lib/queue/drivers/queue_redis.d.ts +2 -1
  18. package/lib/queue/drivers/queue_redis.d.ts.map +1 -1
  19. package/lib/queue/drivers/queue_redis.js +35 -0
  20. package/lib/queue/drivers/queue_redis.js.map +1 -1
  21. package/lib/queue/drivers/queue_sqlite3.d.ts +2 -1
  22. package/lib/queue/drivers/queue_sqlite3.d.ts.map +1 -1
  23. package/lib/queue/drivers/queue_sqlite3.js +36 -6
  24. package/lib/queue/drivers/queue_sqlite3.js.map +1 -1
  25. package/lib/queue/index.d.ts +36 -0
  26. package/lib/queue/index.d.ts.map +1 -1
  27. package/lib/queue/index.js +86 -1
  28. package/lib/queue/index.js.map +1 -1
  29. package/lib/utils/retry.d.ts +66 -0
  30. package/lib/utils/retry.d.ts.map +1 -0
  31. package/lib/utils/retry.js +155 -0
  32. package/lib/utils/retry.js.map +1 -0
  33. package/npm-shrinkwrap.json +5 -28
  34. package/package.json +2 -2
  35. package/services/fx/client.d.ts.map +1 -1
  36. package/services/fx/client.js +19 -9
  37. package/services/fx/client.js.map +1 -1
  38. package/services/fx/server.d.ts.map +1 -1
  39. package/services/fx/server.js +26 -1
  40. package/services/fx/server.js.map +1 -1
  41. package/services/fx/util.d.ts.map +1 -1
  42. package/services/fx/util.js +0 -3
  43. package/services/fx/util.js.map +1 -1
  44. package/services/kyc/iso20022.generated.d.ts +39 -3
  45. package/services/kyc/iso20022.generated.d.ts.map +1 -1
  46. package/services/kyc/iso20022.generated.js +40 -5
  47. package/services/kyc/iso20022.generated.js.map +1 -1
  48. package/services/kyc/oids.generated.d.ts +18 -0
  49. package/services/kyc/oids.generated.d.ts.map +1 -1
  50. package/services/kyc/oids.generated.js +32 -2
  51. package/services/kyc/oids.generated.js.map +1 -1
package/lib/chaining.js CHANGED
@@ -5,10 +5,12 @@ import { Currency } from '@keetanetwork/currency-info';
5
5
  import { isAssetLocationLike } from '../services/asset-movement/lib/location.generated.js';
6
6
  import { isFiatRail, isMovableAssetSearchCanonical, isRail } from '../services/asset-movement/common.generated.js';
7
7
  import { assertNever } from './utils/never.js';
8
+ import { withRetry } from './utils/retry.js';
8
9
  import KeetaFXAnchorClient from '../services/fx/client.js';
9
10
  import KeetaAssetMovementAnchorClient from '../services/asset-movement/client.js';
10
11
  import { isExternalChainAsset, isMovableAssetEqual } from './asset.js';
11
12
  import { AnchorExternalBuilder } from './anchor-external.js';
13
+ import { KeetaAnchorError } from './error.js';
12
14
  ;
13
15
  ;
14
16
  ;
@@ -1330,9 +1332,15 @@ export function listChainingPlanFees(plan) {
1330
1332
  export function isForwardingPlan(plan) {
1331
1333
  const steps = plan.plan.steps;
1332
1334
  if (steps.length === 0) {
1333
- return (false);
1335
+ return ({ isForwardingOnly: false, providerID: null });
1334
1336
  }
1335
- return (steps.every((step) => step.type === 'forwarded'));
1337
+ for (const step of steps) {
1338
+ if (step.type === 'forwarded') {
1339
+ continue;
1340
+ }
1341
+ return ({ isForwardingOnly: false, providerID: step.step?.providerID ?? null });
1342
+ }
1343
+ return ({ isForwardingOnly: true });
1336
1344
  }
1337
1345
  /** Deposit address for the first forwarding leg of a forwarding-only plan. */
1338
1346
  export function getForwardingDepositAddress(plan) {
@@ -1454,6 +1462,43 @@ export class AnchorChainingPath {
1454
1462
  }
1455
1463
  }
1456
1464
  }
1465
+ export class AnchorChainingPlanCreateError extends KeetaAnchorError {
1466
+ static name = 'AnchorChainingPlanCreateError';
1467
+ AnchorChainingPlanCreateErrorObjectTypeID;
1468
+ static AnchorChainingPlanCreateErrorObjectTypeID = '940e318b-a6d1-4f8e-be69-e6de9bc99948';
1469
+ failedAtStep;
1470
+ rootError;
1471
+ constructor(input) {
1472
+ let message = 'Computing Plan Failed';
1473
+ if (KeetaAnchorError.isInstance(input.rootError)) {
1474
+ message = input.rootError.message;
1475
+ }
1476
+ super(message);
1477
+ Object.defineProperty(this, 'AnchorChainingPlanCreateErrorObjectTypeID', {
1478
+ value: AnchorChainingPlanCreateError.AnchorChainingPlanCreateErrorObjectTypeID,
1479
+ enumerable: false
1480
+ });
1481
+ this.rootError = input.rootError;
1482
+ this.failedAtStep = input.failedAtStep;
1483
+ }
1484
+ static isInstance(input) {
1485
+ if (!this.hasPropWithValue(input, 'AnchorChainingPlanCreateErrorObjectTypeID', AnchorChainingPlanCreateError.AnchorChainingPlanCreateErrorObjectTypeID)) {
1486
+ return (false);
1487
+ }
1488
+ return (true);
1489
+ }
1490
+ static resolveErrorResponse(input) {
1491
+ let rootError;
1492
+ let providerID = null;
1493
+ if (input instanceof AnchorChainingPlanCreateError) {
1494
+ rootError = input.rootError;
1495
+ if (input.failedAtStep?.providerID) {
1496
+ providerID = input.failedAtStep.providerID;
1497
+ }
1498
+ }
1499
+ return ({ success: false, error: rootError, failedAt: { providerID } });
1500
+ }
1501
+ }
1457
1502
  export class AnchorChainingPlan extends AnchorChainingPath {
1458
1503
  #_plan = null;
1459
1504
  #state = { status: 'idle' };
@@ -1675,326 +1720,337 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1675
1720
  if (!promise) {
1676
1721
  resolvingSteps.add(index);
1677
1722
  promise = (async () => {
1678
- if (step.type === 'fx') {
1679
- let amount;
1680
- if (affinity === 'from') {
1681
- if (index === 0) {
1682
- amount = affinityAndAmount.amount;
1723
+ try {
1724
+ if (step.type === 'fx') {
1725
+ let amount;
1726
+ if (affinity === 'from') {
1727
+ if (index === 0) {
1728
+ amount = affinityAndAmount.amount;
1729
+ }
1730
+ else {
1731
+ const previous = await resolveStep(index - 1);
1732
+ amount = previous.valueOut;
1733
+ }
1734
+ }
1735
+ else if (affinity === 'to') {
1736
+ if (index === (this.path.length - 1)) {
1737
+ // XXX:TODO Move this to destination
1738
+ amount = affinityAndAmount.amount;
1739
+ }
1740
+ else {
1741
+ const next = await resolveStep(index + 1);
1742
+ amount = next.valueIn;
1743
+ }
1683
1744
  }
1684
1745
  else {
1685
- const previous = await resolveStep(index - 1);
1686
- amount = previous.valueOut;
1746
+ assertNever(affinity);
1687
1747
  }
1688
- }
1689
- else if (affinity === 'to') {
1690
- if (index === (this.path.length - 1)) {
1691
- // XXX:TODO Move this to destination
1692
- amount = affinityAndAmount.amount;
1748
+ const fxAccountOptions = await this.getAccountsForAction({
1749
+ type: 'fx',
1750
+ providerMethod: 'getAccountForAction'
1751
+ }, this.#options?.overrides);
1752
+ const quotesOrEstimates = await fxClient.getQuotesOrEstimates({ from: step.from.asset, to: step.to.asset, amount, affinity }, fxAccountOptions, { providerIDs: [step.providerID] });
1753
+ if (!quotesOrEstimates?.[0] || quotesOrEstimates.length === 0) {
1754
+ throw (new Error(`Could not get FX quote/estimate for provider ${step.providerID}`));
1693
1755
  }
1694
- else {
1695
- const next = await resolveStep(index + 1);
1696
- amount = next.valueIn;
1756
+ const result = quotesOrEstimates[0];
1757
+ if (!result.isQuote && result.estimate.canPerformExchange === false) {
1758
+ throw (new Error(`FX estimate from provider ${step.providerID} indicates exchange cannot be performed`));
1697
1759
  }
1698
- }
1699
- else {
1700
- assertNever(affinity);
1701
- }
1702
- const fxAccountOptions = await this.getAccountsForAction({
1703
- type: 'fx',
1704
- providerMethod: 'getAccountForAction'
1705
- }, this.#options?.overrides);
1706
- const quotesOrEstimates = await fxClient.getQuotesOrEstimates({ from: step.from.asset, to: step.to.asset, amount, affinity }, fxAccountOptions, { providerIDs: [step.providerID] });
1707
- if (!quotesOrEstimates?.[0] || quotesOrEstimates.length === 0) {
1708
- throw (new Error(`Could not get FX quote/estimate for provider ${step.providerID}`));
1709
- }
1710
- const result = quotesOrEstimates[0];
1711
- if (!result.isQuote && result.estimate.canPerformExchange === false) {
1712
- throw (new Error(`FX estimate from provider ${step.providerID} indicates exchange cannot be performed`));
1713
- }
1714
- const convertedAmount = result.isQuote ? result.quote.convertedAmount : result.estimate.convertedAmount;
1715
- let valueIn;
1716
- let valueOut;
1717
- if (affinity === 'to') {
1718
- valueOut = amount;
1719
- valueIn = convertedAmount;
1720
- }
1721
- else if (affinity === 'from') {
1722
- valueOut = convertedAmount;
1723
- valueIn = amount;
1724
- }
1725
- else {
1726
- assertNever(affinity);
1727
- }
1728
- return ({ type: 'fx', step, valueIn, valueOut, result });
1729
- }
1730
- else if (step.type === 'assetMovement') {
1731
- /*
1732
- * Defense in depth: validatePathStructure rejects affinity 'to' on
1733
- * asset-movement steps before any network call. This guard keeps the
1734
- * check next to the operation in case the early pass is bypassed.
1735
- */
1736
- if (affinity === 'to') {
1737
- throw (new Error(`Chaining with affinity 'to' is not currently supported for asset movement steps, as it requires looking up transfer quotes/estimates which is not currently implemented`));
1738
- }
1739
- let depositValue;
1740
- if (index === 0) {
1741
- depositValue = affinityAndAmount.amount;
1742
- }
1743
- else {
1744
- const precomputedPrev = precomputedValueOuts.get(index - 1);
1745
- if (precomputedPrev !== undefined) {
1746
- depositValue = precomputedPrev;
1760
+ const convertedAmount = result.isQuote ? result.quote.convertedAmount : result.estimate.convertedAmount;
1761
+ let valueIn;
1762
+ let valueOut;
1763
+ if (affinity === 'to') {
1764
+ valueOut = amount;
1765
+ valueIn = convertedAmount;
1766
+ }
1767
+ else if (affinity === 'from') {
1768
+ valueOut = convertedAmount;
1769
+ valueIn = amount;
1747
1770
  }
1748
1771
  else {
1749
- const previous = await resolveStep(index - 1);
1750
- depositValue = previous.valueOut;
1772
+ assertNever(affinity);
1751
1773
  }
1774
+ return ({ type: 'fx', step, valueIn, valueOut, result });
1752
1775
  }
1753
- const assetPair = { from: step.from.asset, to: step.to.asset };
1754
- /*
1755
- * Forwarded step: prior step deposits into a pre-resolved persistent address.
1756
- */
1757
- const forwardedInfo = forwardedSteps.get(index);
1758
- if (forwardedInfo) {
1759
- const { provider: forwardedProvider, persistentAddress } = forwardedInfo;
1760
- let estimatedValueOut = depositValue;
1761
- let simulatedTransfer;
1762
- if (forwardingOnly) {
1763
- estimatedValueOut = estimateValueOutFromPersistentForwardingFees(depositValue, persistentAddress.fees);
1776
+ else if (step.type === 'assetMovement') {
1777
+ /*
1778
+ * Defense in depth: validatePathStructure rejects affinity 'to' on
1779
+ * asset-movement steps before any network call. This guard keeps the
1780
+ * check next to the operation in case the early pass is bypassed.
1781
+ */
1782
+ if (affinity === 'to') {
1783
+ throw (new Error(`Chaining with affinity 'to' is not currently supported for asset movement steps, as it requires looking up transfer quotes/estimates which is not currently implemented`));
1764
1784
  }
1765
- else if (await forwardedProvider.isOperationSupported('simulateTransfer')) {
1766
- try {
1767
- const { signer: forwardedSigner } = await this.getAccountsForAction({
1768
- type: 'assetMovement',
1769
- providerMethod: 'initiateTransfer',
1770
- provider: forwardedProvider
1771
- }, this.#options?.overrides);
1772
- simulatedTransfer = await forwardedProvider.simulateTransfer({
1773
- account: forwardedSigner,
1774
- asset: assetPair,
1775
- from: { location: step.from.location },
1776
- to: { location: step.to.location },
1777
- value: depositValue
1778
- });
1779
- const simulatedInstruction = simulatedTransfer.instructions.find((instr) => instr.type === step.from.rail);
1780
- let simulatedTotalReceive;
1781
- if (simulatedInstruction) {
1782
- simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1783
- if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1784
- simulatedTotalReceive = simulatedInstruction.value;
1785
- }
1786
- }
1787
- if (simulatedTotalReceive !== undefined) {
1788
- estimatedValueOut = BigInt(simulatedTotalReceive);
1789
- }
1785
+ let depositValue;
1786
+ if (index === 0) {
1787
+ depositValue = affinityAndAmount.amount;
1788
+ }
1789
+ else {
1790
+ const precomputedPrev = precomputedValueOuts.get(index - 1);
1791
+ if (precomputedPrev !== undefined) {
1792
+ depositValue = precomputedPrev;
1790
1793
  }
1791
- catch (error) {
1792
- this.logger?.debug('AnchorChainingPlan::resolveStep', `simulateTransfer for forwarded step ${index} valueOut estimation failed; falling back to depositValue`, error);
1794
+ else {
1795
+ const previous = await resolveStep(index - 1);
1796
+ depositValue = previous.valueOut;
1793
1797
  }
1794
1798
  }
1795
- return ({
1796
- type: 'forwarded',
1797
- step,
1798
- valueIn: depositValue,
1799
- valueOut: estimatedValueOut,
1800
- persistentAddress,
1801
- provider: forwardedProvider,
1802
- ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1803
- });
1804
- }
1805
- if (this.#options?.forwardingOnly) {
1806
- throw (new Error(`Forwarding-only plan requires persistent forwarding for step at index ${index}, but none was resolved`));
1807
- }
1808
- const providers = await assetMovementClient.getProvidersForTransfer({ asset: assetPair, from: step.from.location, to: step.to.location }, { providerIDs: [step.providerID] });
1809
- if (!providers?.[0] || providers.length === 0) {
1810
- throw (new Error(`Could not get asset movement provider ${step.providerID}`));
1811
- }
1812
- const provider = providers[0];
1813
- const { signer } = await this.getAccountsForAction({
1814
- type: 'assetMovement',
1815
- providerMethod: 'initiateTransfer',
1816
- provider
1817
- }, this.#options?.overrides);
1818
- let resolvedRecipient;
1819
- let sendingToType;
1820
- if (index === this.path.length - 1) {
1821
- resolvedRecipient = this.request.destination.recipient;
1822
- sendingToType = 'FINAL_DESTINATION';
1823
- }
1824
- else {
1825
- sendingToType = 'NEXT_STEP';
1826
- const nextPathStep = this.path[index + 1];
1827
- if (!nextPathStep) {
1828
- throw (new Error(`Expected next step at index ${index + 1} for asset movement step at index ${index}`));
1829
- }
1799
+ const assetPair = { from: step.from.asset, to: step.to.asset };
1830
1800
  /*
1831
- * Next step is forwarded: recipient is its persistent address,
1832
- * no need to resolve the next step's instructions.
1801
+ * Forwarded step: prior step deposits into a pre-resolved persistent address.
1833
1802
  */
1834
- const nextForwardedInfo = forwardedSteps.get(index + 1);
1835
- if (nextForwardedInfo) {
1836
- const pfiAddress = nextForwardedInfo.persistentAddress.address;
1837
- if (typeof pfiAddress !== 'string') {
1838
- throw (new Error(`Persistent forwarding address for next step ${index + 1} is not a resolved string`));
1803
+ const forwardedInfo = forwardedSteps.get(index);
1804
+ if (forwardedInfo) {
1805
+ const { provider: forwardedProvider, persistentAddress } = forwardedInfo;
1806
+ let estimatedValueOut = depositValue;
1807
+ let simulatedTransfer;
1808
+ if (forwardingOnly) {
1809
+ estimatedValueOut = estimateValueOutFromPersistentForwardingFees(depositValue, persistentAddress.fees);
1839
1810
  }
1840
- resolvedRecipient = pfiAddress;
1811
+ else if (await forwardedProvider.isOperationSupported('simulateTransfer')) {
1812
+ try {
1813
+ const { signer: forwardedSigner } = await this.getAccountsForAction({
1814
+ type: 'assetMovement',
1815
+ providerMethod: 'initiateTransfer',
1816
+ provider: forwardedProvider
1817
+ }, this.#options?.overrides);
1818
+ simulatedTransfer = await forwardedProvider.simulateTransfer({
1819
+ account: forwardedSigner,
1820
+ asset: assetPair,
1821
+ from: { location: step.from.location },
1822
+ to: { location: step.to.location },
1823
+ value: depositValue
1824
+ });
1825
+ const simulatedInstruction = simulatedTransfer.instructions.find((instr) => instr.type === step.from.rail);
1826
+ let simulatedTotalReceive;
1827
+ if (simulatedInstruction) {
1828
+ simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1829
+ if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1830
+ simulatedTotalReceive = simulatedInstruction.value;
1831
+ }
1832
+ }
1833
+ if (simulatedTotalReceive !== undefined) {
1834
+ estimatedValueOut = BigInt(simulatedTotalReceive);
1835
+ }
1836
+ }
1837
+ catch (error) {
1838
+ this.logger?.debug('AnchorChainingPlan::resolveStep', `simulateTransfer for forwarded step ${index} valueOut estimation failed; falling back to depositValue`, error);
1839
+ }
1840
+ }
1841
+ return ({
1842
+ type: 'forwarded',
1843
+ step,
1844
+ valueIn: depositValue,
1845
+ valueOut: estimatedValueOut,
1846
+ persistentAddress,
1847
+ provider: forwardedProvider,
1848
+ ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1849
+ });
1841
1850
  }
1842
- else if (nextPathStep.from.location === this.keetaLocation) {
1843
- const { account } = await this.getAccountsForAction({
1844
- type: 'assetMovement',
1845
- providerMethod: 'initiateTransfer'
1846
- }, this.#options?.overrides);
1847
- // Store funds in-transit in the account instead of forwarding directly to provider.
1848
- resolvedRecipient = account;
1851
+ if (this.#options?.forwardingOnly) {
1852
+ throw (new Error(`Forwarding-only plan requires persistent forwarding for step at index ${index}, but none was resolved`));
1853
+ }
1854
+ const providers = await assetMovementClient.getProvidersForTransfer({ asset: assetPair, from: step.from.location, to: step.to.location }, { providerIDs: [step.providerID] });
1855
+ if (!providers?.[0] || providers.length === 0) {
1856
+ throw (new Error(`Could not get asset movement provider ${step.providerID}`));
1857
+ }
1858
+ const provider = providers[0];
1859
+ const { signer } = await this.getAccountsForAction({
1860
+ type: 'assetMovement',
1861
+ providerMethod: 'initiateTransfer',
1862
+ provider
1863
+ }, this.#options?.overrides);
1864
+ let resolvedRecipient;
1865
+ let sendingToType;
1866
+ if (index === this.path.length - 1) {
1867
+ resolvedRecipient = this.request.destination.recipient;
1868
+ sendingToType = 'FINAL_DESTINATION';
1849
1869
  }
1850
1870
  else {
1851
- /**
1852
- * If the provider does not support simulateTransfer,
1853
- * we cannot chain to this step.
1854
- */
1855
- if (!await provider.isOperationSupported('simulateTransfer')) {
1856
- throw (new Error(`Asset movement provider ${step.providerID} does not support simulateTransfer, which is required for chaining at non-keeta intermediate location ${convertAssetLocationToString(nextPathStep.from.location)}`));
1857
- }
1858
- const simulated = await provider.simulateTransfer({
1859
- account: signer,
1860
- asset: assetPair,
1861
- from: { location: step.from.location },
1862
- to: { location: step.to.location },
1863
- value: depositValue
1864
- });
1865
- const simulatedInstruction = simulated.instructions.find((instr) => instr.type === step.from.rail);
1866
- if (!simulatedInstruction) {
1867
- throw (new Error(`Simulated transfer for step ${index} did not return an instruction matching rail ${step.from.rail}`));
1871
+ sendingToType = 'NEXT_STEP';
1872
+ const nextPathStep = this.path[index + 1];
1873
+ if (!nextPathStep) {
1874
+ throw (new Error(`Expected next step at index ${index + 1} for asset movement step at index ${index}`));
1868
1875
  }
1869
- let simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1870
- if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1871
- simulatedTotalReceive = simulatedInstruction.value;
1876
+ /*
1877
+ * Next step is forwarded: recipient is its persistent address,
1878
+ * no need to resolve the next step's instructions.
1879
+ */
1880
+ const nextForwardedInfo = forwardedSteps.get(index + 1);
1881
+ if (nextForwardedInfo) {
1882
+ const pfiAddress = nextForwardedInfo.persistentAddress.address;
1883
+ if (typeof pfiAddress !== 'string') {
1884
+ throw (new Error(`Persistent forwarding address for next step ${index + 1} is not a resolved string`));
1885
+ }
1886
+ resolvedRecipient = pfiAddress;
1872
1887
  }
1873
- if (simulatedTotalReceive === undefined) {
1874
- throw (new Error(`totalReceiveAmount must be defined for simulated transfer when chaining`));
1888
+ else if (nextPathStep.from.location === this.keetaLocation) {
1889
+ const { account } = await this.getAccountsForAction({
1890
+ type: 'assetMovement',
1891
+ providerMethod: 'initiateTransfer'
1892
+ }, this.#options?.overrides);
1893
+ // Store funds in-transit in the account instead of forwarding directly to provider.
1894
+ resolvedRecipient = account;
1875
1895
  }
1876
- precomputedValueOuts.set(index, BigInt(simulatedTotalReceive));
1877
- const nextStep = await resolveStep(index + 1);
1878
- if (nextStep.type === 'assetMovement' || nextStep.type === 'keetaSend') {
1879
- if (nextStep.usingInstruction.type !== step.to.rail) {
1880
- throw (new Error(`Next step's usingInstruction type ${nextStep.usingInstruction.type} does not match expected ${step.to.rail} for recipient resolution`));
1896
+ else {
1897
+ /**
1898
+ * If the provider does not support simulateTransfer,
1899
+ * we cannot chain to this step.
1900
+ */
1901
+ if (!await provider.isOperationSupported('simulateTransfer')) {
1902
+ throw (new Error(`Asset movement provider ${step.providerID} does not support simulateTransfer, which is required for chaining at non-keeta intermediate location ${convertAssetLocationToString(nextPathStep.from.location)}`));
1881
1903
  }
1882
- const foundInstruction = nextStep.usingInstruction;
1883
- const isFiatPushRailFoundInstruction = (input) => {
1884
- return (isFiatRail(input.type));
1885
- };
1886
- if (foundInstruction.type === 'KEETA_SEND') {
1887
- // Structurally unreachable now that validatePathStructure requires a keetaSend step to be the sole step; kept as a defensive invariant.
1888
- throw (new Error(`Cannot currently chain from asset movement to KEETA_SEND step, as this implies multiple keeta locations in the path which is not currently supported`));
1904
+ const simulated = await provider.simulateTransfer({
1905
+ account: signer,
1906
+ asset: assetPair,
1907
+ from: { location: step.from.location },
1908
+ to: { location: step.to.location },
1909
+ value: depositValue
1910
+ });
1911
+ const simulatedInstruction = simulated.instructions.find((instr) => instr.type === step.from.rail);
1912
+ if (!simulatedInstruction) {
1913
+ throw (new Error(`Simulated transfer for step ${index} did not return an instruction matching rail ${step.from.rail}`));
1914
+ }
1915
+ let simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1916
+ if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1917
+ simulatedTotalReceive = simulatedInstruction.value;
1889
1918
  }
1890
- else if (isFiatPushRailFoundInstruction(foundInstruction)) {
1891
- if (foundInstruction.depositMessage) {
1892
- throw (new Error(`Deposit message outbound is not currently supported for chaining`));
1919
+ if (simulatedTotalReceive === undefined) {
1920
+ throw (new Error(`totalReceiveAmount must be defined for simulated transfer when chaining`));
1921
+ }
1922
+ precomputedValueOuts.set(index, BigInt(simulatedTotalReceive));
1923
+ const nextStep = await resolveStep(index + 1);
1924
+ if (nextStep.type === 'assetMovement' || nextStep.type === 'keetaSend') {
1925
+ if (nextStep.usingInstruction.type !== step.to.rail) {
1926
+ throw (new Error(`Next step's usingInstruction type ${nextStep.usingInstruction.type} does not match expected ${step.to.rail} for recipient resolution`));
1927
+ }
1928
+ const foundInstruction = nextStep.usingInstruction;
1929
+ const isFiatPushRailFoundInstruction = (input) => {
1930
+ return (isFiatRail(input.type));
1931
+ };
1932
+ if (foundInstruction.type === 'KEETA_SEND') {
1933
+ // Structurally unreachable now that validatePathStructure requires a keetaSend step to be the sole step; kept as a defensive invariant.
1934
+ throw (new Error(`Cannot currently chain from asset movement to KEETA_SEND step, as this implies multiple keeta locations in the path which is not currently supported`));
1935
+ }
1936
+ else if (isFiatPushRailFoundInstruction(foundInstruction)) {
1937
+ if (foundInstruction.depositMessage) {
1938
+ throw (new Error(`Deposit message outbound is not currently supported for chaining`));
1939
+ }
1940
+ resolvedRecipient = foundInstruction.account;
1941
+ }
1942
+ else if (foundInstruction.type === 'EVM_SEND' || foundInstruction.type === 'SOLANA_SEND') {
1943
+ resolvedRecipient = foundInstruction.sendToAddress;
1944
+ }
1945
+ else {
1946
+ throw (new Error(`Unsupported rail for chaining: ${step.to.rail}`));
1893
1947
  }
1894
- resolvedRecipient = foundInstruction.account;
1895
1948
  }
1896
- else if (foundInstruction.type === 'EVM_SEND' || foundInstruction.type === 'SOLANA_SEND') {
1897
- resolvedRecipient = foundInstruction.sendToAddress;
1949
+ else if (nextStep.type === 'fx') {
1950
+ throw (new Error(`Cannot currently chain from asset movement to fx step, as fx step does not have recipient information`));
1951
+ }
1952
+ else if (nextStep.type === 'forwarded') {
1953
+ throw (new Error(`Internal invariant violation: forwarded step at index ${index + 1} reached simulate-cycle-break path; expected nextForwardedInfo branch to have handled it`));
1898
1954
  }
1899
1955
  else {
1900
- throw (new Error(`Unsupported rail for chaining: ${step.to.rail}`));
1956
+ assertNever(nextStep);
1901
1957
  }
1902
1958
  }
1903
- else if (nextStep.type === 'fx') {
1904
- throw (new Error(`Cannot currently chain from asset movement to fx step, as fx step does not have recipient information`));
1905
- }
1906
- else if (nextStep.type === 'forwarded') {
1907
- throw (new Error(`Internal invariant violation: forwarded step at index ${index + 1} reached simulate-cycle-break path; expected nextForwardedInfo branch to have handled it`));
1908
- }
1909
- else {
1910
- assertNever(nextStep);
1911
- }
1912
1959
  }
1960
+ const recipientString = KeetaNet.lib.Account.isInstance(resolvedRecipient)
1961
+ ? resolvedRecipient.publicKeyString.get()
1962
+ : resolvedRecipient;
1963
+ const transfer = await provider.initiateTransfer({
1964
+ account: signer,
1965
+ asset: assetPair,
1966
+ from: { location: step.from.location },
1967
+ to: {
1968
+ location: step.to.location,
1969
+ recipient: recipientString
1970
+ },
1971
+ value: depositValue
1972
+ });
1973
+ const usingInstruction = findInstruction(transfer.instructions, step.from.rail);
1974
+ let totalReceiveAmount = usingInstruction.totalReceiveAmount;
1975
+ if (totalReceiveAmount === undefined && 'value' in usingInstruction) {
1976
+ totalReceiveAmount = usingInstruction.value;
1977
+ }
1978
+ if (totalReceiveAmount === undefined) {
1979
+ throw (new Error(`totalReceiveAmount must be defined for chaining`));
1980
+ }
1981
+ const actualValueOut = BigInt(totalReceiveAmount);
1982
+ // If we simulated to break a cycle, the next step's initiateTransfer was
1983
+ // keyed off the simulated valueOut; a mismatch here means the next step
1984
+ // is now misaligned, so fail at plan-time instead of letting execute() catch it.
1985
+ const simulatedValueOut = precomputedValueOuts.get(index);
1986
+ if (simulatedValueOut !== undefined && simulatedValueOut !== actualValueOut) {
1987
+ throw (new Error(`Simulated valueOut ${simulatedValueOut} for step ${index} does not match actual ${actualValueOut} from initiateTransfer`));
1988
+ }
1989
+ return ({
1990
+ type: 'assetMovement',
1991
+ step: step,
1992
+ valueIn: depositValue,
1993
+ usingInstruction: usingInstruction,
1994
+ transfer: transfer,
1995
+ sendingTo: sendingToType,
1996
+ valueOut: actualValueOut,
1997
+ provider: provider
1998
+ });
1913
1999
  }
1914
- const recipientString = KeetaNet.lib.Account.isInstance(resolvedRecipient)
1915
- ? resolvedRecipient.publicKeyString.get()
1916
- : resolvedRecipient;
1917
- const transfer = await provider.initiateTransfer({
1918
- account: signer,
1919
- asset: assetPair,
1920
- from: { location: step.from.location },
1921
- to: {
1922
- location: step.to.location,
1923
- recipient: recipientString
1924
- },
1925
- value: depositValue
1926
- });
1927
- const usingInstruction = findInstruction(transfer.instructions, step.from.rail);
1928
- let totalReceiveAmount = usingInstruction.totalReceiveAmount;
1929
- if (totalReceiveAmount === undefined && 'value' in usingInstruction) {
1930
- totalReceiveAmount = usingInstruction.value;
1931
- }
1932
- if (totalReceiveAmount === undefined) {
1933
- throw (new Error(`totalReceiveAmount must be defined for chaining`));
1934
- }
1935
- const actualValueOut = BigInt(totalReceiveAmount);
1936
- // If we simulated to break a cycle, the next step's initiateTransfer was
1937
- // keyed off the simulated valueOut; a mismatch here means the next step
1938
- // is now misaligned, so fail at plan-time instead of letting execute() catch it.
1939
- const simulatedValueOut = precomputedValueOuts.get(index);
1940
- if (simulatedValueOut !== undefined && simulatedValueOut !== actualValueOut) {
1941
- throw (new Error(`Simulated valueOut ${simulatedValueOut} for step ${index} does not match actual ${actualValueOut} from initiateTransfer`));
1942
- }
1943
- return ({
1944
- type: 'assetMovement',
1945
- step: step,
1946
- valueIn: depositValue,
1947
- usingInstruction: usingInstruction,
1948
- transfer: transfer,
1949
- sendingTo: sendingToType,
1950
- valueOut: actualValueOut,
1951
- provider: provider
1952
- });
1953
- }
1954
- else if (step.type === 'keetaSend') {
1955
- // Defense in depth: validatePathStructure also enforces this early.
1956
- if (this.path.length !== 1) {
1957
- throw (new Error(`Direct same-location/same-asset send steps must be the only step in the path`));
1958
- }
1959
- if (!KeetaNet.lib.Account.isInstance(step.from.asset) || !KeetaNet.lib.Account.isInstance(step.to.asset)) {
1960
- throw (new Error(`Expected assets to be token accounts for KEETA_SEND rail`));
1961
- }
1962
- if (!step.from.asset.comparePublicKey(step.to.asset)) {
1963
- throw (new Error(`For KEETA_SEND step, from and to asset must be the same account`));
1964
- }
1965
- let keetaRecipientDestination = null;
1966
- if (KeetaNet.lib.Account.isInstance(this.request.destination.recipient)) {
1967
- keetaRecipientDestination = this.request.destination.recipient;
1968
- }
1969
- else if (typeof this.request.destination.recipient === 'string') {
1970
- try {
1971
- keetaRecipientDestination = KeetaNet.lib.Account.fromPublicKeyString(this.request.destination.recipient);
2000
+ else if (step.type === 'keetaSend') {
2001
+ // Defense in depth: validatePathStructure also enforces this early.
2002
+ if (this.path.length !== 1) {
2003
+ throw (new Error(`Direct same-location/same-asset send steps must be the only step in the path`));
2004
+ }
2005
+ if (!KeetaNet.lib.Account.isInstance(step.from.asset) || !KeetaNet.lib.Account.isInstance(step.to.asset)) {
2006
+ throw (new Error(`Expected assets to be token accounts for KEETA_SEND rail`));
1972
2007
  }
1973
- catch {
1974
- /* ignore errors */
2008
+ if (!step.from.asset.comparePublicKey(step.to.asset)) {
2009
+ throw (new Error(`For KEETA_SEND step, from and to asset must be the same account`));
1975
2010
  }
2011
+ let keetaRecipientDestination = null;
2012
+ if (KeetaNet.lib.Account.isInstance(this.request.destination.recipient)) {
2013
+ keetaRecipientDestination = this.request.destination.recipient;
2014
+ }
2015
+ else if (typeof this.request.destination.recipient === 'string') {
2016
+ try {
2017
+ keetaRecipientDestination = KeetaNet.lib.Account.fromPublicKeyString(this.request.destination.recipient);
2018
+ }
2019
+ catch {
2020
+ /* ignore errors */
2021
+ }
2022
+ }
2023
+ if (!keetaRecipientDestination) {
2024
+ throw (new Error(`Expected destination recipient to be a public key string for KEETA_SEND step`));
2025
+ }
2026
+ return ({
2027
+ type: 'keetaSend',
2028
+ step: null,
2029
+ valueIn: affinityAndAmount.amount,
2030
+ valueOut: affinityAndAmount.amount,
2031
+ usingInstruction: {
2032
+ type: 'KEETA_SEND',
2033
+ tokenAddress: step.to.asset.publicKeyString.get(),
2034
+ sendToAddress: keetaRecipientDestination.publicKeyString.get(),
2035
+ totalReceiveAmount: affinityAndAmount.amount.toString(),
2036
+ location: `chain:keeta:${this.parent['client'].network}`,
2037
+ value: String(affinityAndAmount.amount),
2038
+ assetFee: '0'
2039
+ }
2040
+ });
1976
2041
  }
1977
- if (!keetaRecipientDestination) {
1978
- throw (new Error(`Expected destination recipient to be a public key string for KEETA_SEND step`));
2042
+ else {
2043
+ assertNever(step);
1979
2044
  }
1980
- return ({
1981
- type: 'keetaSend',
1982
- step: null,
1983
- valueIn: affinityAndAmount.amount,
1984
- valueOut: affinityAndAmount.amount,
1985
- usingInstruction: {
1986
- type: 'KEETA_SEND',
1987
- tokenAddress: step.to.asset.publicKeyString.get(),
1988
- sendToAddress: keetaRecipientDestination.publicKeyString.get(),
1989
- totalReceiveAmount: affinityAndAmount.amount.toString(),
1990
- location: `chain:keeta:${this.parent['client'].network}`,
1991
- value: String(affinityAndAmount.amount),
1992
- assetFee: '0'
1993
- }
1994
- });
1995
2045
  }
1996
- else {
1997
- assertNever(step);
2046
+ catch (error) {
2047
+ if (error instanceof AnchorChainingPlanCreateError) {
2048
+ throw (error);
2049
+ }
2050
+ throw (new AnchorChainingPlanCreateError({
2051
+ rootError: error,
2052
+ failedAtStep: step
2053
+ }));
1998
2054
  }
1999
2055
  })();
2000
2056
  promise.then(() => resolvingSteps.delete(index), () => resolvingSteps.delete(index));
@@ -2160,6 +2216,19 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2160
2216
  const external = await builder.build();
2161
2217
  return (external);
2162
2218
  }
2219
+ /**
2220
+ * Retry policy for a single status poll.
2221
+ */
2222
+ #pollRetryOptions(scope, deadline, options) {
2223
+ const remainingMs = Math.max(0, deadline - Date.now());
2224
+ return ({
2225
+ ...options?.poll,
2226
+ maxTotalMs: Math.min(options?.poll?.maxTotalMs ?? remainingMs, remainingMs),
2227
+ loggerContext: scope,
2228
+ ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {}),
2229
+ ...(this.logger ? { logger: this.logger } : {})
2230
+ });
2231
+ }
2163
2232
  async #pollTransferStatus(transfer, context, options) {
2164
2233
  const intervalMs = options?.intervalMs ?? 2000;
2165
2234
  const timeoutMs = options?.timeoutMs ?? 300_000;
@@ -2168,7 +2237,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2168
2237
  if (options?.abortSignal?.aborted) {
2169
2238
  throw (new Error(`Aborted while waiting for transfer ${transfer.transferID} to complete`));
2170
2239
  }
2171
- const status = await transfer.getTransferStatus();
2240
+ const status = await withRetry(async function () {
2241
+ return (await transfer.getTransferStatus());
2242
+ }, this.#pollRetryOptions('AnchorChainingPlan::pollTransferStatus', deadline, options));
2172
2243
  this.#emit('transactionObserved', {
2173
2244
  stepIndex: context.stepIndex,
2174
2245
  planStep: context.planStep,
@@ -2247,7 +2318,9 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2247
2318
  if (options?.abortSignal?.aborted) {
2248
2319
  throw (new Error(`Aborted while waiting for FX exchange ${exchange.exchange.exchangeID} to complete`));
2249
2320
  }
2250
- const status = await exchange.getExchangeStatus();
2321
+ const status = await withRetry(async function () {
2322
+ return (await exchange.getExchangeStatus());
2323
+ }, this.#pollRetryOptions('AnchorChainingPlan::pollExchangeStatus', deadline, options));
2251
2324
  if (status.status === 'completed') {
2252
2325
  return (status);
2253
2326
  }
@@ -2317,7 +2390,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2317
2390
  }
2318
2391
  if (step.type === 'fx') {
2319
2392
  const exchange = await step.result.createExchange(undefined, { inputs: [...publishedInputs] });
2320
- const exchangeStatus = await this.#pollExchangeStatus(exchange);
2393
+ const exchangeStatus = await this.#pollExchangeStatus(exchange, options);
2321
2394
  publishedInputs.push({ blockHash: exchangeStatus.blockhash });
2322
2395
  prevActualValueOut = step.valueOut;
2323
2396
  prevWithdrawTx = null;
@@ -2327,9 +2400,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2327
2400
  if (!prevWithdrawTx) {
2328
2401
  throw (new Error(`Forwarded step at index ${index} requires the prior step to produce a withdraw transaction on its destination chain`));
2329
2402
  }
2330
- const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, pollContext, {
2331
- ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
2332
- });
2403
+ const observed = await this.#pollForwardedTransaction(step, prevWithdrawTx, pollContext, options);
2333
2404
  prevActualValueOut = BigInt(observed.to.value);
2334
2405
  prevWithdrawTx = null;
2335
2406
  onStepCompleted({ type: 'forwarded', plan: step, observedTransaction: observed });
@@ -2369,9 +2440,7 @@ export class AnchorChainingPlan extends AnchorChainingPath {
2369
2440
  throw (new Error(`Unsupported instruction type ${step.usingInstruction.type} for user-initiated transfer at step ${index}`));
2370
2441
  }
2371
2442
  if (step.type === 'assetMovement') {
2372
- const status = await this.#pollTransferStatus(step.transfer, pollContext, {
2373
- ...(options?.abortSignal ? { abortSignal: options.abortSignal } : {})
2374
- });
2443
+ const status = await this.#pollTransferStatus(step.transfer, pollContext, options);
2375
2444
  prevActualValueOut = BigInt(status.transaction.to.value);
2376
2445
  const withdraw = status.transaction.to.transactions.withdraw;
2377
2446
  if (withdraw) {
@@ -2604,23 +2673,29 @@ export class AnchorChaining {
2604
2673
  }
2605
2674
  if (options?.includeAllOutput) {
2606
2675
  if (plan.status === 'rejected') {
2607
- ret.push({ success: false, error: plan.reason, path });
2608
- }
2609
- else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2610
- ret.push({ success: false, error: new Error('Plan does not qualify as a forwarding-only route'), path });
2611
- }
2612
- else if (plan.value instanceof AnchorChainingForwardingOnlyPlan) {
2613
- ret.push({ success: true, plan: plan.value, path });
2676
+ ret.push({
2677
+ ...(AnchorChainingPlanCreateError.resolveErrorResponse(plan.reason)),
2678
+ path
2679
+ });
2614
2680
  }
2615
- else if (plan.value instanceof AnchorChainingPlan) {
2616
- ret.push({ success: true, plan: plan.value, path });
2681
+ else {
2682
+ const isForwardingPlanResult = isForwardingPlan(plan.value);
2683
+ if (forwardingOpts && !isForwardingPlanResult.isForwardingOnly) {
2684
+ ret.push({ success: false, error: new Error('Plan does not qualify as a forwarding-only route'), path, failedAt: { providerID: isForwardingPlanResult.providerID } });
2685
+ }
2686
+ else if (plan.value instanceof AnchorChainingForwardingOnlyPlan) {
2687
+ ret.push({ success: true, plan: plan.value, path });
2688
+ }
2689
+ else if (plan.value instanceof AnchorChainingPlan) {
2690
+ ret.push({ success: true, plan: plan.value, path });
2691
+ }
2617
2692
  }
2618
2693
  }
2619
2694
  else {
2620
2695
  if (plan.status === 'rejected') {
2621
2696
  this.logger?.debug(`AnchorChaining::getPlans`, `Error computing plan for a path:`, plan.reason);
2622
2697
  }
2623
- else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2698
+ else if (forwardingOpts && !isForwardingPlan(plan.value).isForwardingOnly) {
2624
2699
  this.logger?.debug(`AnchorChaining::getPlans`, `Skipping plan that does not qualify as forwarding-only`);
2625
2700
  }
2626
2701
  else {