@keetanetwork/anchor 0.0.96 → 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 (39) hide show
  1. package/lib/chaining.d.ts +29 -9
  2. package/lib/chaining.d.ts.map +1 -1
  3. package/lib/chaining.js +356 -295
  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/npm-shrinkwrap.json +5 -28
  30. package/package.json +2 -2
  31. package/services/fx/client.d.ts.map +1 -1
  32. package/services/fx/client.js +19 -9
  33. package/services/fx/client.js.map +1 -1
  34. package/services/fx/server.d.ts.map +1 -1
  35. package/services/fx/server.js +26 -1
  36. package/services/fx/server.js.map +1 -1
  37. package/services/fx/util.d.ts.map +1 -1
  38. package/services/fx/util.js +0 -3
  39. package/services/fx/util.js.map +1 -1
package/lib/chaining.js CHANGED
@@ -10,6 +10,7 @@ import KeetaFXAnchorClient from '../services/fx/client.js';
10
10
  import KeetaAssetMovementAnchorClient from '../services/asset-movement/client.js';
11
11
  import { isExternalChainAsset, isMovableAssetEqual } from './asset.js';
12
12
  import { AnchorExternalBuilder } from './anchor-external.js';
13
+ import { KeetaAnchorError } from './error.js';
13
14
  ;
14
15
  ;
15
16
  ;
@@ -1331,9 +1332,15 @@ export function listChainingPlanFees(plan) {
1331
1332
  export function isForwardingPlan(plan) {
1332
1333
  const steps = plan.plan.steps;
1333
1334
  if (steps.length === 0) {
1334
- return (false);
1335
+ return ({ isForwardingOnly: false, providerID: null });
1335
1336
  }
1336
- 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 });
1337
1344
  }
1338
1345
  /** Deposit address for the first forwarding leg of a forwarding-only plan. */
1339
1346
  export function getForwardingDepositAddress(plan) {
@@ -1455,6 +1462,43 @@ export class AnchorChainingPath {
1455
1462
  }
1456
1463
  }
1457
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
+ }
1458
1502
  export class AnchorChainingPlan extends AnchorChainingPath {
1459
1503
  #_plan = null;
1460
1504
  #state = { status: 'idle' };
@@ -1676,326 +1720,337 @@ export class AnchorChainingPlan extends AnchorChainingPath {
1676
1720
  if (!promise) {
1677
1721
  resolvingSteps.add(index);
1678
1722
  promise = (async () => {
1679
- if (step.type === 'fx') {
1680
- let amount;
1681
- if (affinity === 'from') {
1682
- if (index === 0) {
1683
- 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
+ }
1684
1744
  }
1685
1745
  else {
1686
- const previous = await resolveStep(index - 1);
1687
- amount = previous.valueOut;
1746
+ assertNever(affinity);
1688
1747
  }
1689
- }
1690
- else if (affinity === 'to') {
1691
- if (index === (this.path.length - 1)) {
1692
- // XXX:TODO Move this to destination
1693
- 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}`));
1694
1755
  }
1695
- else {
1696
- const next = await resolveStep(index + 1);
1697
- 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`));
1698
1759
  }
1699
- }
1700
- else {
1701
- assertNever(affinity);
1702
- }
1703
- const fxAccountOptions = await this.getAccountsForAction({
1704
- type: 'fx',
1705
- providerMethod: 'getAccountForAction'
1706
- }, this.#options?.overrides);
1707
- const quotesOrEstimates = await fxClient.getQuotesOrEstimates({ from: step.from.asset, to: step.to.asset, amount, affinity }, fxAccountOptions, { providerIDs: [step.providerID] });
1708
- if (!quotesOrEstimates?.[0] || quotesOrEstimates.length === 0) {
1709
- throw (new Error(`Could not get FX quote/estimate for provider ${step.providerID}`));
1710
- }
1711
- const result = quotesOrEstimates[0];
1712
- if (!result.isQuote && result.estimate.canPerformExchange === false) {
1713
- throw (new Error(`FX estimate from provider ${step.providerID} indicates exchange cannot be performed`));
1714
- }
1715
- const convertedAmount = result.isQuote ? result.quote.convertedAmount : result.estimate.convertedAmount;
1716
- let valueIn;
1717
- let valueOut;
1718
- if (affinity === 'to') {
1719
- valueOut = amount;
1720
- valueIn = convertedAmount;
1721
- }
1722
- else if (affinity === 'from') {
1723
- valueOut = convertedAmount;
1724
- valueIn = amount;
1725
- }
1726
- else {
1727
- assertNever(affinity);
1728
- }
1729
- return ({ type: 'fx', step, valueIn, valueOut, result });
1730
- }
1731
- else if (step.type === 'assetMovement') {
1732
- /*
1733
- * Defense in depth: validatePathStructure rejects affinity 'to' on
1734
- * asset-movement steps before any network call. This guard keeps the
1735
- * check next to the operation in case the early pass is bypassed.
1736
- */
1737
- if (affinity === 'to') {
1738
- 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`));
1739
- }
1740
- let depositValue;
1741
- if (index === 0) {
1742
- depositValue = affinityAndAmount.amount;
1743
- }
1744
- else {
1745
- const precomputedPrev = precomputedValueOuts.get(index - 1);
1746
- if (precomputedPrev !== undefined) {
1747
- 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;
1748
1770
  }
1749
1771
  else {
1750
- const previous = await resolveStep(index - 1);
1751
- depositValue = previous.valueOut;
1772
+ assertNever(affinity);
1752
1773
  }
1774
+ return ({ type: 'fx', step, valueIn, valueOut, result });
1753
1775
  }
1754
- const assetPair = { from: step.from.asset, to: step.to.asset };
1755
- /*
1756
- * Forwarded step: prior step deposits into a pre-resolved persistent address.
1757
- */
1758
- const forwardedInfo = forwardedSteps.get(index);
1759
- if (forwardedInfo) {
1760
- const { provider: forwardedProvider, persistentAddress } = forwardedInfo;
1761
- let estimatedValueOut = depositValue;
1762
- let simulatedTransfer;
1763
- if (forwardingOnly) {
1764
- 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`));
1765
1784
  }
1766
- else if (await forwardedProvider.isOperationSupported('simulateTransfer')) {
1767
- try {
1768
- const { signer: forwardedSigner } = await this.getAccountsForAction({
1769
- type: 'assetMovement',
1770
- providerMethod: 'initiateTransfer',
1771
- provider: forwardedProvider
1772
- }, this.#options?.overrides);
1773
- simulatedTransfer = await forwardedProvider.simulateTransfer({
1774
- account: forwardedSigner,
1775
- asset: assetPair,
1776
- from: { location: step.from.location },
1777
- to: { location: step.to.location },
1778
- value: depositValue
1779
- });
1780
- const simulatedInstruction = simulatedTransfer.instructions.find((instr) => instr.type === step.from.rail);
1781
- let simulatedTotalReceive;
1782
- if (simulatedInstruction) {
1783
- simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1784
- if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1785
- simulatedTotalReceive = simulatedInstruction.value;
1786
- }
1787
- }
1788
- if (simulatedTotalReceive !== undefined) {
1789
- estimatedValueOut = BigInt(simulatedTotalReceive);
1790
- }
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;
1791
1793
  }
1792
- catch (error) {
1793
- 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;
1794
1797
  }
1795
1798
  }
1796
- return ({
1797
- type: 'forwarded',
1798
- step,
1799
- valueIn: depositValue,
1800
- valueOut: estimatedValueOut,
1801
- persistentAddress,
1802
- provider: forwardedProvider,
1803
- ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1804
- });
1805
- }
1806
- if (this.#options?.forwardingOnly) {
1807
- throw (new Error(`Forwarding-only plan requires persistent forwarding for step at index ${index}, but none was resolved`));
1808
- }
1809
- const providers = await assetMovementClient.getProvidersForTransfer({ asset: assetPair, from: step.from.location, to: step.to.location }, { providerIDs: [step.providerID] });
1810
- if (!providers?.[0] || providers.length === 0) {
1811
- throw (new Error(`Could not get asset movement provider ${step.providerID}`));
1812
- }
1813
- const provider = providers[0];
1814
- const { signer } = await this.getAccountsForAction({
1815
- type: 'assetMovement',
1816
- providerMethod: 'initiateTransfer',
1817
- provider
1818
- }, this.#options?.overrides);
1819
- let resolvedRecipient;
1820
- let sendingToType;
1821
- if (index === this.path.length - 1) {
1822
- resolvedRecipient = this.request.destination.recipient;
1823
- sendingToType = 'FINAL_DESTINATION';
1824
- }
1825
- else {
1826
- sendingToType = 'NEXT_STEP';
1827
- const nextPathStep = this.path[index + 1];
1828
- if (!nextPathStep) {
1829
- throw (new Error(`Expected next step at index ${index + 1} for asset movement step at index ${index}`));
1830
- }
1799
+ const assetPair = { from: step.from.asset, to: step.to.asset };
1831
1800
  /*
1832
- * Next step is forwarded: recipient is its persistent address,
1833
- * no need to resolve the next step's instructions.
1801
+ * Forwarded step: prior step deposits into a pre-resolved persistent address.
1834
1802
  */
1835
- const nextForwardedInfo = forwardedSteps.get(index + 1);
1836
- if (nextForwardedInfo) {
1837
- const pfiAddress = nextForwardedInfo.persistentAddress.address;
1838
- if (typeof pfiAddress !== 'string') {
1839
- 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);
1810
+ }
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
1840
  }
1841
- resolvedRecipient = pfiAddress;
1841
+ return ({
1842
+ type: 'forwarded',
1843
+ step,
1844
+ valueIn: depositValue,
1845
+ valueOut: estimatedValueOut,
1846
+ persistentAddress,
1847
+ provider: forwardedProvider,
1848
+ ...(simulatedTransfer !== undefined ? { simulatedTransfer } : {})
1849
+ });
1850
+ }
1851
+ if (this.#options?.forwardingOnly) {
1852
+ throw (new Error(`Forwarding-only plan requires persistent forwarding for step at index ${index}, but none was resolved`));
1842
1853
  }
1843
- else if (nextPathStep.from.location === this.keetaLocation) {
1844
- const { account } = await this.getAccountsForAction({
1845
- type: 'assetMovement',
1846
- providerMethod: 'initiateTransfer'
1847
- }, this.#options?.overrides);
1848
- // Store funds in-transit in the account instead of forwarding directly to provider.
1849
- resolvedRecipient = account;
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';
1850
1869
  }
1851
1870
  else {
1852
- /**
1853
- * If the provider does not support simulateTransfer,
1854
- * we cannot chain to this step.
1855
- */
1856
- if (!await provider.isOperationSupported('simulateTransfer')) {
1857
- 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)}`));
1858
- }
1859
- const simulated = await provider.simulateTransfer({
1860
- account: signer,
1861
- asset: assetPair,
1862
- from: { location: step.from.location },
1863
- to: { location: step.to.location },
1864
- value: depositValue
1865
- });
1866
- const simulatedInstruction = simulated.instructions.find((instr) => instr.type === step.from.rail);
1867
- if (!simulatedInstruction) {
1868
- 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}`));
1869
1875
  }
1870
- let simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1871
- if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1872
- 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;
1873
1887
  }
1874
- if (simulatedTotalReceive === undefined) {
1875
- 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;
1876
1895
  }
1877
- precomputedValueOuts.set(index, BigInt(simulatedTotalReceive));
1878
- const nextStep = await resolveStep(index + 1);
1879
- if (nextStep.type === 'assetMovement' || nextStep.type === 'keetaSend') {
1880
- if (nextStep.usingInstruction.type !== step.to.rail) {
1881
- 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)}`));
1903
+ }
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}`));
1882
1914
  }
1883
- const foundInstruction = nextStep.usingInstruction;
1884
- const isFiatPushRailFoundInstruction = (input) => {
1885
- return (isFiatRail(input.type));
1886
- };
1887
- if (foundInstruction.type === 'KEETA_SEND') {
1888
- // Structurally unreachable now that validatePathStructure requires a keetaSend step to be the sole step; kept as a defensive invariant.
1889
- 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`));
1915
+ let simulatedTotalReceive = simulatedInstruction.totalReceiveAmount;
1916
+ if (simulatedTotalReceive === undefined && 'value' in simulatedInstruction) {
1917
+ simulatedTotalReceive = simulatedInstruction.value;
1890
1918
  }
1891
- else if (isFiatPushRailFoundInstruction(foundInstruction)) {
1892
- if (foundInstruction.depositMessage) {
1893
- 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`));
1894
1935
  }
1895
- resolvedRecipient = foundInstruction.account;
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}`));
1947
+ }
1948
+ }
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`));
1896
1951
  }
1897
- else if (foundInstruction.type === 'EVM_SEND' || foundInstruction.type === 'SOLANA_SEND') {
1898
- resolvedRecipient = foundInstruction.sendToAddress;
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`));
1899
1954
  }
1900
1955
  else {
1901
- throw (new Error(`Unsupported rail for chaining: ${step.to.rail}`));
1956
+ assertNever(nextStep);
1902
1957
  }
1903
1958
  }
1904
- else if (nextStep.type === 'fx') {
1905
- throw (new Error(`Cannot currently chain from asset movement to fx step, as fx step does not have recipient information`));
1906
- }
1907
- else if (nextStep.type === 'forwarded') {
1908
- throw (new Error(`Internal invariant violation: forwarded step at index ${index + 1} reached simulate-cycle-break path; expected nextForwardedInfo branch to have handled it`));
1909
- }
1910
- else {
1911
- assertNever(nextStep);
1912
- }
1913
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
+ });
1914
1999
  }
1915
- const recipientString = KeetaNet.lib.Account.isInstance(resolvedRecipient)
1916
- ? resolvedRecipient.publicKeyString.get()
1917
- : resolvedRecipient;
1918
- const transfer = await provider.initiateTransfer({
1919
- account: signer,
1920
- asset: assetPair,
1921
- from: { location: step.from.location },
1922
- to: {
1923
- location: step.to.location,
1924
- recipient: recipientString
1925
- },
1926
- value: depositValue
1927
- });
1928
- const usingInstruction = findInstruction(transfer.instructions, step.from.rail);
1929
- let totalReceiveAmount = usingInstruction.totalReceiveAmount;
1930
- if (totalReceiveAmount === undefined && 'value' in usingInstruction) {
1931
- totalReceiveAmount = usingInstruction.value;
1932
- }
1933
- if (totalReceiveAmount === undefined) {
1934
- throw (new Error(`totalReceiveAmount must be defined for chaining`));
1935
- }
1936
- const actualValueOut = BigInt(totalReceiveAmount);
1937
- // If we simulated to break a cycle, the next step's initiateTransfer was
1938
- // keyed off the simulated valueOut; a mismatch here means the next step
1939
- // is now misaligned, so fail at plan-time instead of letting execute() catch it.
1940
- const simulatedValueOut = precomputedValueOuts.get(index);
1941
- if (simulatedValueOut !== undefined && simulatedValueOut !== actualValueOut) {
1942
- throw (new Error(`Simulated valueOut ${simulatedValueOut} for step ${index} does not match actual ${actualValueOut} from initiateTransfer`));
1943
- }
1944
- return ({
1945
- type: 'assetMovement',
1946
- step: step,
1947
- valueIn: depositValue,
1948
- usingInstruction: usingInstruction,
1949
- transfer: transfer,
1950
- sendingTo: sendingToType,
1951
- valueOut: actualValueOut,
1952
- provider: provider
1953
- });
1954
- }
1955
- else if (step.type === 'keetaSend') {
1956
- // Defense in depth: validatePathStructure also enforces this early.
1957
- if (this.path.length !== 1) {
1958
- throw (new Error(`Direct same-location/same-asset send steps must be the only step in the path`));
1959
- }
1960
- if (!KeetaNet.lib.Account.isInstance(step.from.asset) || !KeetaNet.lib.Account.isInstance(step.to.asset)) {
1961
- throw (new Error(`Expected assets to be token accounts for KEETA_SEND rail`));
1962
- }
1963
- if (!step.from.asset.comparePublicKey(step.to.asset)) {
1964
- throw (new Error(`For KEETA_SEND step, from and to asset must be the same account`));
1965
- }
1966
- let keetaRecipientDestination = null;
1967
- if (KeetaNet.lib.Account.isInstance(this.request.destination.recipient)) {
1968
- keetaRecipientDestination = this.request.destination.recipient;
1969
- }
1970
- else if (typeof this.request.destination.recipient === 'string') {
1971
- try {
1972
- 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`));
2007
+ }
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`));
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
+ }
1973
2022
  }
1974
- catch {
1975
- /* ignore errors */
2023
+ if (!keetaRecipientDestination) {
2024
+ throw (new Error(`Expected destination recipient to be a public key string for KEETA_SEND step`));
1976
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
+ });
1977
2041
  }
1978
- if (!keetaRecipientDestination) {
1979
- throw (new Error(`Expected destination recipient to be a public key string for KEETA_SEND step`));
2042
+ else {
2043
+ assertNever(step);
1980
2044
  }
1981
- return ({
1982
- type: 'keetaSend',
1983
- step: null,
1984
- valueIn: affinityAndAmount.amount,
1985
- valueOut: affinityAndAmount.amount,
1986
- usingInstruction: {
1987
- type: 'KEETA_SEND',
1988
- tokenAddress: step.to.asset.publicKeyString.get(),
1989
- sendToAddress: keetaRecipientDestination.publicKeyString.get(),
1990
- totalReceiveAmount: affinityAndAmount.amount.toString(),
1991
- location: `chain:keeta:${this.parent['client'].network}`,
1992
- value: String(affinityAndAmount.amount),
1993
- assetFee: '0'
1994
- }
1995
- });
1996
2045
  }
1997
- else {
1998
- 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
+ }));
1999
2054
  }
2000
2055
  })();
2001
2056
  promise.then(() => resolvingSteps.delete(index), () => resolvingSteps.delete(index));
@@ -2618,23 +2673,29 @@ export class AnchorChaining {
2618
2673
  }
2619
2674
  if (options?.includeAllOutput) {
2620
2675
  if (plan.status === 'rejected') {
2621
- ret.push({ success: false, error: plan.reason, path });
2622
- }
2623
- else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2624
- ret.push({ success: false, error: new Error('Plan does not qualify as a forwarding-only route'), path });
2625
- }
2626
- else if (plan.value instanceof AnchorChainingForwardingOnlyPlan) {
2627
- ret.push({ success: true, plan: plan.value, path });
2676
+ ret.push({
2677
+ ...(AnchorChainingPlanCreateError.resolveErrorResponse(plan.reason)),
2678
+ path
2679
+ });
2628
2680
  }
2629
- else if (plan.value instanceof AnchorChainingPlan) {
2630
- 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
+ }
2631
2692
  }
2632
2693
  }
2633
2694
  else {
2634
2695
  if (plan.status === 'rejected') {
2635
2696
  this.logger?.debug(`AnchorChaining::getPlans`, `Error computing plan for a path:`, plan.reason);
2636
2697
  }
2637
- else if (forwardingOpts && !isForwardingPlan(plan.value)) {
2698
+ else if (forwardingOpts && !isForwardingPlan(plan.value).isForwardingOnly) {
2638
2699
  this.logger?.debug(`AnchorChaining::getPlans`, `Skipping plan that does not qualify as forwarding-only`);
2639
2700
  }
2640
2701
  else {