@lifi/sdk-provider-stellar 0.0.0-preview-c328023 → 4.2.0

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 (75) hide show
  1. package/CHANGELOG.md +9 -5
  2. package/dist/esm/StellarProvider.d.ts +7 -1
  3. package/dist/esm/StellarProvider.d.ts.map +1 -1
  4. package/dist/esm/StellarProvider.js +8 -2
  5. package/dist/esm/StellarProvider.js.map +1 -1
  6. package/dist/esm/actions/getStellarBalance.js +14 -5
  7. package/dist/esm/actions/getStellarBalance.js.map +1 -1
  8. package/dist/esm/actions/resolveStellarAddress.d.ts +8 -1
  9. package/dist/esm/actions/resolveStellarAddress.d.ts.map +1 -1
  10. package/dist/esm/actions/resolveStellarAddress.js +11 -2
  11. package/dist/esm/actions/resolveStellarAddress.js.map +1 -1
  12. package/dist/esm/client/getStellarRpc.d.ts +3 -3
  13. package/dist/esm/client/getStellarRpc.d.ts.map +1 -1
  14. package/dist/esm/client/getStellarRpc.js +2 -2
  15. package/dist/esm/client/getStellarRpc.js.map +1 -1
  16. package/dist/esm/core/StellarStepExecutor.d.ts.map +1 -1
  17. package/dist/esm/core/StellarStepExecutor.js +3 -1
  18. package/dist/esm/core/StellarStepExecutor.js.map +1 -1
  19. package/dist/esm/core/tasks/StellarPrepareTransactionTask.d.ts +23 -16
  20. package/dist/esm/core/tasks/StellarPrepareTransactionTask.d.ts.map +1 -1
  21. package/dist/esm/core/tasks/StellarPrepareTransactionTask.js +28 -28
  22. package/dist/esm/core/tasks/StellarPrepareTransactionTask.js.map +1 -1
  23. package/dist/esm/core/tasks/StellarWaitForTransactionTask.d.ts.map +1 -1
  24. package/dist/esm/core/tasks/StellarWaitForTransactionTask.js +17 -3
  25. package/dist/esm/core/tasks/StellarWaitForTransactionTask.js.map +1 -1
  26. package/dist/esm/core/tasks/helpers/assertApprovalStillCovers.d.ts +21 -0
  27. package/dist/esm/core/tasks/helpers/assertApprovalStillCovers.d.ts.map +1 -0
  28. package/dist/esm/core/tasks/helpers/assertApprovalStillCovers.js +29 -0
  29. package/dist/esm/core/tasks/helpers/assertApprovalStillCovers.js.map +1 -0
  30. package/dist/esm/core/tasks/helpers/probeStellarTransaction.d.ts +20 -0
  31. package/dist/esm/core/tasks/helpers/probeStellarTransaction.d.ts.map +1 -0
  32. package/dist/esm/core/tasks/helpers/probeStellarTransaction.js +20 -0
  33. package/dist/esm/core/tasks/helpers/probeStellarTransaction.js.map +1 -0
  34. package/dist/esm/core/tasks/helpers/readAllowance.d.ts +4 -0
  35. package/dist/esm/core/tasks/helpers/readAllowance.d.ts.map +1 -1
  36. package/dist/esm/core/tasks/helpers/readAllowance.js +12 -6
  37. package/dist/esm/core/tasks/helpers/readAllowance.js.map +1 -1
  38. package/dist/esm/core/tasks/helpers/resolveApprovalRequirement.js +1 -2
  39. package/dist/esm/core/tasks/helpers/resolveApprovalRequirement.js.map +1 -1
  40. package/dist/esm/core/tasks/helpers/submitStellarTransaction.d.ts +3 -0
  41. package/dist/esm/core/tasks/helpers/submitStellarTransaction.d.ts.map +1 -1
  42. package/dist/esm/core/tasks/helpers/submitStellarTransaction.js +20 -6
  43. package/dist/esm/core/tasks/helpers/submitStellarTransaction.js.map +1 -1
  44. package/dist/esm/core/tasks/helpers/waitForStellarTransaction.d.ts +8 -4
  45. package/dist/esm/core/tasks/helpers/waitForStellarTransaction.d.ts.map +1 -1
  46. package/dist/esm/core/tasks/helpers/waitForStellarTransaction.js +26 -9
  47. package/dist/esm/core/tasks/helpers/waitForStellarTransaction.js.map +1 -1
  48. package/dist/esm/errors/parseStellarErrors.js +7 -2
  49. package/dist/esm/errors/parseStellarErrors.js.map +1 -1
  50. package/dist/esm/index.d.ts +2 -2
  51. package/dist/esm/index.js +2 -2
  52. package/dist/esm/types.d.ts +10 -6
  53. package/dist/esm/types.d.ts.map +1 -1
  54. package/dist/esm/types.js.map +1 -1
  55. package/dist/esm/version.d.ts +1 -1
  56. package/dist/esm/version.js +1 -1
  57. package/dist/esm/version.js.map +1 -1
  58. package/package.json +3 -3
  59. package/src/StellarProvider.ts +8 -1
  60. package/src/actions/getStellarBalance.ts +22 -6
  61. package/src/actions/resolveStellarAddress.ts +19 -2
  62. package/src/client/getStellarRpc.ts +6 -8
  63. package/src/core/StellarStepExecutor.ts +11 -0
  64. package/src/core/tasks/StellarPrepareTransactionTask.ts +31 -71
  65. package/src/core/tasks/StellarWaitForTransactionTask.ts +35 -7
  66. package/src/core/tasks/helpers/assertApprovalStillCovers.ts +48 -0
  67. package/src/core/tasks/helpers/probeStellarTransaction.ts +34 -0
  68. package/src/core/tasks/helpers/readAllowance.ts +42 -33
  69. package/src/core/tasks/helpers/resolveApprovalRequirement.ts +10 -10
  70. package/src/core/tasks/helpers/submitStellarTransaction.ts +41 -25
  71. package/src/core/tasks/helpers/waitForStellarTransaction.ts +44 -20
  72. package/src/errors/parseStellarErrors.ts +17 -5
  73. package/src/index.ts +4 -1
  74. package/src/types.ts +10 -6
  75. package/src/version.ts +1 -1
@@ -10,10 +10,10 @@ import {
10
10
  BASE_FEE,
11
11
  Contract,
12
12
  Networks,
13
- rpc,
14
13
  scValToNative,
15
14
  TransactionBuilder,
16
15
  } from '@stellar/stellar-sdk'
16
+ import { Api } from '@stellar/stellar-sdk/rpc'
17
17
  import { callStellarRpcsWithRetry } from '../client/getStellarRpc.js'
18
18
 
19
19
  type SacBalanceResult = {
@@ -47,23 +47,39 @@ export const getStellarBalance = async (
47
47
  withDedupe(
48
48
  () => getSacBalance(client, walletAddress, token, networkPassphrase),
49
49
  { id: `${getStellarBalance.name}.${walletAddress}.${token.address}` }
50
- ).catch(() => undefined)
50
+ ).then(
51
+ (value) => ({ value, error: undefined as Error | undefined }),
52
+ (error) => ({
53
+ value: undefined,
54
+ error: error instanceof Error ? error : new Error(String(error)),
55
+ })
56
+ )
51
57
  )
52
58
  )
53
59
 
60
+ // Every read failed — the RPC list is unreachable, or the chain is not served
61
+ // at all. Returning tokens with neither an amount nor a blockNumber reads to
62
+ // consumers as a balance that has yet to settle, so they would poll forever
63
+ // instead of seeing the failure.
64
+ const firstError = results.find((result) => result.error)?.error
65
+ if (firstError && results.every((result) => !result.value)) {
66
+ throw firstError
67
+ }
68
+
54
69
  // Consumers treat a missing blockNumber as an unsettled read and keep
55
70
  // polling, so every token must carry one. The ledger rides along on the
56
71
  // simulation response; a token whose read threw borrows the batch's newest.
57
72
  const fallbackBlockNumber = results.reduce<bigint | undefined>(
58
73
  (latest, result) =>
59
- result && (latest === undefined || result.latestLedger > latest)
60
- ? result.latestLedger
74
+ result.value &&
75
+ (latest === undefined || result.value.latestLedger > latest)
76
+ ? result.value.latestLedger
61
77
  : latest,
62
78
  undefined
63
79
  )
64
80
 
65
81
  return tokens.map((token, index) => {
66
- const result = results[index]
82
+ const result = results[index].value
67
83
  const blockNumber = result?.latestLedger ?? fallbackBlockNumber
68
84
  return result?.amount !== undefined
69
85
  ? { ...token, amount: result.amount, blockNumber }
@@ -99,7 +115,7 @@ const getSacBalance = async (
99
115
 
100
116
  const simulation = await server.simulateTransaction(transaction)
101
117
  const latestLedger = BigInt(simulation.latestLedger)
102
- if (!rpc.Api.isSimulationSuccess(simulation) || !simulation.result) {
118
+ if (!Api.isSimulationSuccess(simulation) || !simulation.result) {
103
119
  return { amount: undefined, latestLedger }
104
120
  }
105
121
  const value = scValToNative(simulation.result.retval)
@@ -3,7 +3,14 @@ import { Federation, StrKey } from '@stellar/stellar-sdk'
3
3
  /**
4
4
  * Resolves a Stellar Federation address (SEP-2, `name*domain.com`) to a G-address.
5
5
  * Returns the input unchanged when it is already a valid G-address, and
6
- * `undefined` when it is neither a federation address nor resolvable.
6
+ * `undefined` when it is neither a federation address nor safely resolvable.
7
+ *
8
+ * `Federation` is imported statically on purpose. Loading it through
9
+ * `await import('@stellar/stellar-sdk')` was measured at +110 KB in the initial
10
+ * chunk: a dynamic import of the root asks for the whole namespace, which
11
+ * cannot be tree-shaken, so Horizon, WebAuth, Friendbot and StellarToml all
12
+ * materialise — and the entry's own static import of the root keeps that chunk
13
+ * eager anyway.
7
14
  */
8
15
  export async function resolveStellarAddress(
9
16
  name: string
@@ -16,7 +23,17 @@ export async function resolveStellarAddress(
16
23
  }
17
24
  try {
18
25
  const record = await Federation.Server.resolve(name)
19
- return record.account_id
26
+ // A memo is part of the destination for a custodial account, and neither
27
+ // the SDK nor the route request can carry one. Resolving to the bare pooled
28
+ // address would deliver funds nobody can attribute, so refuse instead.
29
+ if (record.memo || record.memo_type) {
30
+ return undefined
31
+ }
32
+ // The record comes from an arbitrary remote federation server. Re-apply the
33
+ // G-address-only rule `isStellarAddress` exists to enforce.
34
+ return StrKey.isValidEd25519PublicKey(record.account_id)
35
+ ? record.account_id
36
+ : undefined
20
37
  } catch {
21
38
  return undefined
22
39
  }
@@ -1,7 +1,7 @@
1
1
  import { ChainId, LruMap, type SDKClient } from '@lifi/sdk'
2
- import { rpc } from '@stellar/stellar-sdk'
2
+ import { Server } from '@stellar/stellar-sdk/rpc'
3
3
 
4
- const stellarRpcs = new LruMap<rpc.Server>(12)
4
+ const stellarRpcs = new LruMap<Server>(12)
5
5
 
6
6
  /**
7
7
  * Resolves and caches a Stellar RPC (JSON-RPC / Soroban RPC) server for each RPC
@@ -11,19 +11,17 @@ const ensureStellarRpcs = async (client: SDKClient): Promise<string[]> => {
11
11
  const rpcUrls = await client.getRpcUrlsByChainId(ChainId.XLM)
12
12
  for (const rpcUrl of rpcUrls) {
13
13
  if (!stellarRpcs.has(rpcUrl)) {
14
- stellarRpcs.set(rpcUrl, new rpc.Server(rpcUrl, { allowHttp: true }))
14
+ stellarRpcs.set(rpcUrl, new Server(rpcUrl, { allowHttp: true }))
15
15
  }
16
16
  }
17
17
  return rpcUrls
18
18
  }
19
19
 
20
- export const getStellarRpcs = async (
21
- client: SDKClient
22
- ): Promise<rpc.Server[]> => {
20
+ export const getStellarRpcs = async (client: SDKClient): Promise<Server[]> => {
23
21
  const rpcUrls = await ensureStellarRpcs(client)
24
22
  return rpcUrls
25
23
  .map((rpcUrl) => stellarRpcs.get(rpcUrl))
26
- .filter((server): server is rpc.Server => Boolean(server))
24
+ .filter((server): server is Server => Boolean(server))
27
25
  }
28
26
 
29
27
  /**
@@ -32,7 +30,7 @@ export const getStellarRpcs = async (
32
30
  */
33
31
  export const callStellarRpcsWithRetry = async <R>(
34
32
  client: SDKClient,
35
- fn: (server: rpc.Server) => Promise<R>
33
+ fn: (server: Server) => Promise<R>
36
34
  ): Promise<R> => {
37
35
  const servers = await getStellarRpcs(client)
38
36
  if (servers.length === 0) {
@@ -40,6 +40,17 @@ export class StellarStepExecutor extends BaseStepExecutor {
40
40
  'The wallet address that requested the quote does not match the wallet address attempting to sign the transaction.'
41
41
  )
42
42
  }
43
+
44
+ // The provider resolves this from options first and the wallet second, so a
45
+ // disagreement means the integrator configured one network while the user
46
+ // connected to another. Signing would produce a txBAD_AUTH the user pays
47
+ // for in a wasted signature.
48
+ if (this.networkPassphrase !== this.wallet.networkPassphrase) {
49
+ throw new TransactionError(
50
+ LiFiErrorCode.ChainSwitchError,
51
+ 'The connected Stellar wallet is on a different network than the route.'
52
+ )
53
+ }
43
54
  }
44
55
 
45
56
  override parseErrors = (
@@ -1,81 +1,41 @@
1
- import {
2
- BaseStepExecutionTask,
3
- getStepTransaction,
4
- LiFiErrorCode,
5
- stepComparison,
6
- type TaskResult,
7
- TransactionError,
8
- } from '@lifi/sdk'
1
+ import { PrepareTransactionTask, type TaskResult } from '@lifi/sdk'
9
2
  import type { StellarStepExecutorContext } from '../../types.js'
3
+ import { assertApprovalStillCovers } from './helpers/assertApprovalStillCovers.js'
10
4
 
11
5
  /**
12
- * Re-fetches the step transaction from the backend, **unconditionally**.
6
+ * Always re-fetches the step transaction, where the base task asks only when
7
+ * the step carries none.
13
8
  *
14
- * Do not reintroduce the base task's `if (!step.transactionRequest)` guard. A
15
- * Stellar envelope is not a reusable payload: the backend embeds the sender's
16
- * account sequence number and timebounds `[0, now + 300s]` at build time. Two
17
- * things follow.
9
+ * A Stellar envelope is not a reusable payload: the backend embeds the sender's
10
+ * account sequence number and timebounds `[0, now + 300s]` at build time.
18
11
  *
19
- * 1. Staleness. On the quote path `convertQuoteToRoute` carries the quote's
20
- * `transactionRequest` into the route, so the guarded base task would never
12
+ * 1. Approvals. `StellarSetAllowanceTask` submits a transaction of its own,
13
+ * which consumes the sender's sequence number. Any envelope built before
14
+ * that approval is invalid (`tx_bad_seq`), so the envelope has to be
15
+ * requested after it — which only happens if this task always asks for a
16
+ * fresh one.
17
+ * 2. Staleness. On the quote path `convertQuoteToRoute` carries the quote's
18
+ * `transactionRequest` into the route, so the base guard would never
21
19
  * re-fetch and would sign an envelope minted minutes earlier — expiring as
22
- * `tx_too_late` once the user lingers in their wallet. The retry path has the
23
- * same problem: it resets `step.execution` but not `step.transactionRequest`.
24
- * 2. Approvals. `StellarSetAllowanceTask` submits a transaction of its own, which
25
- * consumes the sender's sequence number. Any envelope built before that
26
- * approval is invalid (`tx_bad_seq`), so the envelope has to be requested
27
- * after it — which only happens if this task always asks for a fresh one.
20
+ * `tx_too_late` once the user lingers in their wallet.
21
+ *
22
+ * The `getRoutes` path never carries a `transactionRequest`, and `resumeRoute`
23
+ * clears it through `prepareRestart`, so the base guard already re-fetches for
24
+ * both. This override is what covers the quote path.
25
+ *
26
+ * Re-quoting also invalidates the allowance the pipeline just granted, so the
27
+ * refreshed route is re-checked against the chain before the step is signed.
28
28
  */
29
- export class StellarPrepareTransactionTask extends BaseStepExecutionTask {
30
- async run(context: StellarStepExecutorContext): Promise<TaskResult> {
31
- const {
32
- client,
33
- step,
34
- statusManager,
35
- allowUserInteraction,
36
- executionOptions,
37
- isBridgeExecution,
38
- } = context
39
-
40
- const action = statusManager.findAction(
41
- step,
42
- isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'
43
- )
44
-
45
- if (!action) {
46
- throw new TransactionError(
47
- LiFiErrorCode.TransactionUnprepared,
48
- 'Unable to prepare transaction. Action not found.'
49
- )
50
- }
51
-
52
- const { execution: _execution, ...stepBase } = step
53
- const updatedStep = await getStepTransaction(client, stepBase)
54
- const comparedStep = await stepComparison(
55
- statusManager,
56
- step,
57
- updatedStep,
58
- allowUserInteraction,
59
- executionOptions
60
- )
61
- Object.assign(step, {
62
- ...comparedStep,
63
- execution: step.execution,
64
- })
65
-
66
- if (!step.transactionRequest?.data) {
67
- throw new TransactionError(
68
- LiFiErrorCode.TransactionUnprepared,
69
- 'Unable to prepare transaction. Transaction request data is not found.'
70
- )
71
- }
72
-
73
- statusManager.updateAction(step, action.type, 'ACTION_REQUIRED')
74
-
75
- if (!allowUserInteraction) {
76
- return { status: 'PAUSED' }
77
- }
29
+ export class StellarPrepareTransactionTask extends PrepareTransactionTask {
30
+ protected override shouldRefetchTransaction(): boolean {
31
+ return true
32
+ }
78
33
 
79
- return { status: 'COMPLETED' }
34
+ override async run(context: StellarStepExecutorContext): Promise<TaskResult> {
35
+ const result = await super.run(context)
36
+ // The refresh above may have re-quoted the route around a different
37
+ // adapter or amount than the allowance was granted for.
38
+ await assertApprovalStillCovers(context)
39
+ return result
80
40
  }
81
41
  }
@@ -1,10 +1,12 @@
1
1
  import {
2
+ BaseError,
2
3
  BaseStepExecutionTask,
3
4
  LiFiErrorCode,
4
5
  type TaskResult,
5
6
  TransactionError,
6
7
  } from '@lifi/sdk'
7
8
  import type { StellarStepExecutorContext } from '../../types.js'
9
+ import { probeStellarTransaction } from './helpers/probeStellarTransaction.js'
8
10
  import { submitStellarTransaction } from './helpers/submitStellarTransaction.js'
9
11
  import { waitForStellarTransaction } from './helpers/waitForStellarTransaction.js'
10
12
 
@@ -46,16 +48,42 @@ export class StellarWaitForTransactionTask extends BaseStepExecutionTask {
46
48
  }
47
49
 
48
50
  // Resuming: the hash is persisted before submission, so the envelope may
49
- // never have reached the network. Re-submit it before polling — Soroban
50
- // submission is idempotent by hash and reports an already-known envelope as
51
- // DUPLICATE, which submitStellarTransaction treats as success. Without this,
52
- // a crash between persisting and submitting would strand the step polling
53
- // for a transaction that was never broadcast.
51
+ // never have reached the network — but it may equally have been applied
52
+ // already, in which case its sequence number is spent and re-submitting can
53
+ // only fail. Ask the network first, and let the poll below decide the
54
+ // outcome either way.
55
+ let resubmitError: unknown
54
56
  if (!transactionHash && action.txHex) {
55
- await submitStellarTransaction(client, action.txHex, networkPassphrase)
57
+ const probe = await probeStellarTransaction(client, hash)
58
+ if (probe !== 'landed') {
59
+ try {
60
+ await submitStellarTransaction(
61
+ client,
62
+ action.txHex,
63
+ networkPassphrase
64
+ )
65
+ } catch (error) {
66
+ // Keep it only when the probe was definite. After a failed probe this
67
+ // may be a txBAD_SEQ from a swap that in fact settled.
68
+ resubmitError = probe === 'not-found' ? error : undefined
69
+ }
70
+ }
56
71
  }
57
72
 
58
- await waitForStellarTransaction(client, hash, pollingIntervalMs)
73
+ try {
74
+ await waitForStellarTransaction(client, hash, pollingIntervalMs)
75
+ } catch (error) {
76
+ // The envelope never reached the network, and the poll can only report
77
+ // that as a timeout. The submission error says why.
78
+ if (
79
+ resubmitError &&
80
+ error instanceof BaseError &&
81
+ error.code === LiFiErrorCode.Timeout
82
+ ) {
83
+ throw resubmitError
84
+ }
85
+ throw error
86
+ }
59
87
 
60
88
  if (isBridgeExecution) {
61
89
  statusManager.updateAction(step, action.type, 'DONE')
@@ -0,0 +1,48 @@
1
+ import { LiFiErrorCode, TransactionError } from '@lifi/sdk'
2
+ import type { StellarStepExecutorContext } from '../../../types.js'
3
+ import { readAllowance } from './readAllowance.js'
4
+ import { resolveApprovalRequirement } from './resolveApprovalRequirement.js'
5
+
6
+ /**
7
+ * Fails the step before signing when the refreshed route needs an allowance the
8
+ * sender does not have.
9
+ *
10
+ * `StellarPrepareTransactionTask` re-quotes after `StellarSetAllowanceTask` has
11
+ * already written an allowance, and the re-quote replaces `includedSteps` and
12
+ * `estimate` wholesale. A fresh quote that names a different adapter, a
13
+ * different intermediate token, or a larger amount would revert `transfer_from`
14
+ * on-chain after a second signature.
15
+ *
16
+ * The check reads the chain rather than comparing against the resolved
17
+ * requirement: when the allowance already existed, the on-chain ceiling can be
18
+ * far above what this route asked for, and comparing the two would reject a
19
+ * route that works.
20
+ */
21
+ export const assertApprovalStillCovers = async (
22
+ context: StellarStepExecutorContext
23
+ ): Promise<void> => {
24
+ // Nothing was resolved before the refresh, so there is no grant to invalidate.
25
+ if (!context.approval) {
26
+ return
27
+ }
28
+
29
+ const refreshed = resolveApprovalRequirement(context.step)
30
+ if (!refreshed) {
31
+ return
32
+ }
33
+
34
+ const allowance = await readAllowance(
35
+ context.client,
36
+ refreshed.tokenAddress,
37
+ context.wallet.address,
38
+ refreshed.spender,
39
+ context.networkPassphrase
40
+ )
41
+
42
+ if (allowance < refreshed.amount) {
43
+ throw new TransactionError(
44
+ LiFiErrorCode.TransactionUnprepared,
45
+ 'The refreshed Stellar route needs a token allowance the sender has not granted. Please request a new route.'
46
+ )
47
+ }
48
+ }
@@ -0,0 +1,34 @@
1
+ import type { SDKClient } from '@lifi/sdk'
2
+ import { Api } from '@stellar/stellar-sdk/rpc'
3
+ import { callStellarRpcsWithRetry } from '../../../client/getStellarRpc.js'
4
+
5
+ /**
6
+ * What the network could tell us about a hash.
7
+ *
8
+ * `'not-found'` and `'unknown'` both mean "re-submit", but only `'not-found'`
9
+ * is a definite answer. A re-submit error after `'unknown'` may come from a
10
+ * transaction that in fact settled, so the caller must not report it.
11
+ */
12
+ export type StellarTransactionProbe = 'landed' | 'not-found' | 'unknown'
13
+
14
+ /**
15
+ * Asks whether the network already knows a transaction, without waiting for it.
16
+ *
17
+ * Soroban RPC only knows a transaction once it has been applied, so `NOT_FOUND`
18
+ * stays ambiguous — never broadcast, or broadcast and still pending.
19
+ */
20
+ export const probeStellarTransaction = async (
21
+ client: SDKClient,
22
+ transactionHash: string
23
+ ): Promise<StellarTransactionProbe> => {
24
+ try {
25
+ const response = await callStellarRpcsWithRetry(client, (server) =>
26
+ server.getTransaction(transactionHash)
27
+ )
28
+ return response.status === Api.GetTransactionStatus.NOT_FOUND
29
+ ? 'not-found'
30
+ : 'landed'
31
+ } catch {
32
+ return 'unknown'
33
+ }
34
+ }
@@ -4,10 +4,10 @@ import {
4
4
  Address,
5
5
  BASE_FEE,
6
6
  Contract,
7
- rpc,
8
7
  scValToNative,
9
8
  TransactionBuilder,
10
9
  } from '@stellar/stellar-sdk'
10
+ import { Api } from '@stellar/stellar-sdk/rpc'
11
11
  import { callStellarRpcsWithRetry } from '../../../client/getStellarRpc.js'
12
12
 
13
13
  /**
@@ -15,6 +15,10 @@ import { callStellarRpcsWithRetry } from '../../../client/getStellarRpc.js'
15
15
  *
16
16
  * An absent or expired allowance entry reads back as `0`, so callers can treat
17
17
  * the result as a plain numeric comparison without a separate existence check.
18
+ *
19
+ * The simulation is the only part that goes through `callStellarRpcsWithRetry`;
20
+ * the result is classified outside it, so a deterministic contract-level failure
21
+ * is not retried against every RPC and is not buried in an `AggregateError`.
18
22
  */
19
23
  export const readAllowance = async (
20
24
  client: SDKClient,
@@ -22,37 +26,42 @@ export const readAllowance = async (
22
26
  from: string,
23
27
  spender: string,
24
28
  networkPassphrase: string
25
- ): Promise<bigint> =>
26
- callStellarRpcsWithRetry(client, async (server) => {
27
- // A zero-sequence account is sufficient for read-only simulation.
28
- const source = new Account(from, '0')
29
- const transaction = new TransactionBuilder(source, {
30
- fee: BASE_FEE,
31
- networkPassphrase,
32
- })
33
- .addOperation(
34
- new Contract(token).call(
35
- 'allowance',
36
- Address.fromString(from).toScVal(),
37
- Address.fromString(spender).toScVal()
38
- )
29
+ ): Promise<bigint> => {
30
+ // A zero-sequence account is sufficient for read-only simulation, and one
31
+ // built envelope is reusable across servers because nothing about it is
32
+ // server-specific.
33
+ const source = new Account(from, '0')
34
+ const transaction = new TransactionBuilder(source, {
35
+ fee: BASE_FEE,
36
+ networkPassphrase,
37
+ })
38
+ .addOperation(
39
+ new Contract(token).call(
40
+ 'allowance',
41
+ Address.fromString(from).toScVal(),
42
+ Address.fromString(spender).toScVal()
39
43
  )
40
- .setTimeout(30)
41
- .build()
44
+ )
45
+ .setTimeout(30)
46
+ .build()
42
47
 
43
- const simulation = await server.simulateTransaction(transaction)
44
- // Fail rather than degrade to 0n: an unreadable allowance treated as "needs
45
- // approval" would prompt the user for an approval that cannot help.
46
- // Classified here rather than left as a bare Error so parseStellarErrors
47
- // passes it through untouched instead of pattern-matching the message.
48
- if (!rpc.Api.isSimulationSuccess(simulation) || !simulation.result) {
49
- throw new TransactionError(
50
- LiFiErrorCode.TransactionSimulationFailed,
51
- `Could not read the ${token} spending allowance for ${spender}${
52
- rpc.Api.isSimulationError(simulation) ? `: ${simulation.error}` : ''
53
- }`
54
- )
55
- }
56
- const allowance = scValToNative(simulation.result.retval)
57
- return allowance != null ? BigInt(allowance) : 0n
58
- })
48
+ // Only the transport call goes through the failover wrapper. It collapses
49
+ // everything its callback throws into an `AggregateError`, so classifying
50
+ // inside it would hide the error below from `parseStellarErrors`.
51
+ const simulation = await callStellarRpcsWithRetry(client, (server) =>
52
+ server.simulateTransaction(transaction)
53
+ )
54
+
55
+ // Fail rather than degrade to 0n: an unreadable allowance treated as "needs
56
+ // approval" would prompt the user for an approval that cannot help.
57
+ if (!Api.isSimulationSuccess(simulation) || !simulation.result) {
58
+ throw new TransactionError(
59
+ LiFiErrorCode.TransactionSimulationFailed,
60
+ `Could not read the ${token} spending allowance for ${spender}${
61
+ Api.isSimulationError(simulation) ? `: ${simulation.error}` : ''
62
+ }`
63
+ )
64
+ }
65
+ const allowance = scValToNative(simulation.result.retval)
66
+ return allowance != null ? BigInt(allowance) : 0n
67
+ }
@@ -35,22 +35,22 @@ export const resolveApprovalRequirement = (
35
35
  step: LiFiStep
36
36
  ): StellarApprovalRequirement | undefined => {
37
37
  // The pipeline grants at most one allowance per step, so the first leg that
38
- // needs one wins. Routes today ask for a single approval; a route whose legs
39
- // pull two different tokens would need the executor to loop instead.
38
+ // needs one wins. A spender also has to be a real Soroban contract (`C`)
39
+ // address: anything else — a `G` wallet, an EVM address — cannot call
40
+ // `transfer_from`, so it is a placeholder rather than a reason to stop
41
+ // looking. Routes today ask for a single approval; a route whose legs pull
42
+ // two different tokens would need the executor to loop instead.
40
43
  const includedStep = step.includedSteps?.find(
41
- (includedStep) => !includedStep.estimate.skipApproval
44
+ (includedStep) =>
45
+ !includedStep.estimate.skipApproval &&
46
+ !!includedStep.estimate.approvalAddress &&
47
+ StrKey.isValidContract(includedStep.estimate.approvalAddress)
42
48
  )
43
49
  if (!includedStep) {
44
50
  return undefined
45
51
  }
46
52
 
47
- const spender = includedStep.estimate.approvalAddress
48
- // A spender has to be a real Soroban contract (`C`) address. Anything else —
49
- // a `G` wallet, an EVM address — cannot call `transfer_from`, so approving it
50
- // would be a wasted signature rather than a step towards a working route.
51
- if (!spender || !StrKey.isValidContract(spender)) {
52
- return undefined
53
- }
53
+ const spender = includedStep.estimate.approvalAddress as string
54
54
 
55
55
  // `fromAmount` is a quote-time figure. A leg fed by an upstream swap is handed
56
56
  // whatever that swap actually produced, which can land above the quote, and
@@ -1,11 +1,16 @@
1
1
  import { LiFiErrorCode, type SDKClient, TransactionError } from '@lifi/sdk'
2
- import {
3
- type rpc,
4
- type Transaction,
5
- TransactionBuilder,
6
- } from '@stellar/stellar-sdk'
2
+ import { type Transaction, TransactionBuilder } from '@stellar/stellar-sdk'
3
+ import type { Api } from '@stellar/stellar-sdk/rpc'
7
4
  import { callStellarRpcsWithRetry } from '../../../client/getStellarRpc.js'
8
5
 
6
+ /**
7
+ * `TRY_AGAIN_LATER` says the envelope is valid but was not queued, so the fix
8
+ * is to send the same envelope again. Submission is idempotent by hash, which
9
+ * makes the retry free of side effects.
10
+ */
11
+ const TRY_AGAIN_ATTEMPTS = 3
12
+ const TRY_AGAIN_DELAY_MS = 2_000
13
+
9
14
  /**
10
15
  * Submits a signed base64 envelope over Stellar RPC and returns the hash.
11
16
  *
@@ -19,6 +24,9 @@ import { callStellarRpcsWithRetry } from '../../../client/getStellarRpc.js'
19
24
  * the network, the expected outcome when failover retries a submission the first
20
25
  * RPC had in fact accepted. Soroban submission is idempotent by hash, so the
21
26
  * right move is to stop resubmitting and start polling.
27
+ *
28
+ * `TRY_AGAIN_LATER` is retried a bounded number of times rather than thrown:
29
+ * core is telling us the envelope was not queued, not that it is invalid.
22
30
  */
23
31
  export const submitStellarTransaction = async (
24
32
  client: SDKClient,
@@ -30,26 +38,34 @@ export const submitStellarTransaction = async (
30
38
  networkPassphrase
31
39
  ) as Transaction
32
40
 
33
- const response: rpc.Api.SendTransactionResponse =
34
- await callStellarRpcsWithRetry(client, (server) =>
35
- server.sendTransaction(transaction)
36
- )
37
-
38
- switch (response.status) {
39
- case 'PENDING':
40
- case 'DUPLICATE':
41
- return response.hash
42
- case 'TRY_AGAIN_LATER':
43
- throw new TransactionError(
44
- LiFiErrorCode.RateLimitExceeded,
45
- 'Stellar RPC asked to try again later.'
46
- )
47
- default:
48
- throw new TransactionError(
49
- LiFiErrorCode.TransactionFailed,
50
- `Stellar transaction submission failed: ${
51
- response.errorResult?.result().switch().name ?? response.status
52
- }`
41
+ for (let attempt = 0; attempt < TRY_AGAIN_ATTEMPTS; attempt++) {
42
+ const response: Api.SendTransactionResponse =
43
+ await callStellarRpcsWithRetry(client, (server) =>
44
+ server.sendTransaction(transaction)
53
45
  )
46
+
47
+ switch (response.status) {
48
+ case 'PENDING':
49
+ case 'DUPLICATE':
50
+ return response.hash
51
+ case 'TRY_AGAIN_LATER':
52
+ break
53
+ default:
54
+ throw new TransactionError(
55
+ LiFiErrorCode.TransactionFailed,
56
+ `Stellar transaction submission failed: ${
57
+ response.errorResult?.result().switch().name ?? response.status
58
+ }`
59
+ )
60
+ }
61
+
62
+ if (attempt < TRY_AGAIN_ATTEMPTS - 1) {
63
+ await new Promise((resolve) => setTimeout(resolve, TRY_AGAIN_DELAY_MS))
64
+ }
54
65
  }
66
+
67
+ throw new TransactionError(
68
+ LiFiErrorCode.RateLimitExceeded,
69
+ 'Stellar RPC asked to try again later.'
70
+ )
55
71
  }