@axis-markets/client 0.8.3 → 0.9.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.
package/src/errors.js CHANGED
@@ -1,4 +1,4 @@
1
- import {contract} from '@stellar/stellar-sdk'
1
+ import {StrKey, contract} from '@stellar/stellar-sdk'
2
2
 
3
3
  /**
4
4
  * Standard contract errors
@@ -59,22 +59,34 @@ export function processSimulationErrors(tx) {
59
59
  const contractErrorMatch = /HostError: Error\(Contract, #(\d+)\)/.exec(message)
60
60
  if (contractErrorMatch) {
61
61
  const code = parseInt(contractErrorMatch[1], 10)
62
- const source = findErrorSource(message, code)
63
- const dexContract = tx.options?.contractId
64
- const raisedByToken = source && dexContract ? source.contract !== dexContract : !ContractErrors[code] && !!TokenErrors[code]
65
- if (raisedByToken)
66
- throw tokenError(code, source?.contract)
67
- const err = ContractErrors[code]
68
- if (err) {
69
- const error = new Error(`Contract execution error: #${code} ${err.message}`)
70
- error.code = code
62
+ const error = contractError(code, findErrorSource(message, code)?.contract, tx.options?.contractId)
63
+ if (error)
71
64
  throw error
72
- }
73
65
  }
74
66
  throw message
75
67
  }
76
68
  }
77
69
 
70
+ /**
71
+ * Wrapped aggregated error - token error when another contract than the DEX raised it, a DEX contract error otherwise
72
+ * @param {number} code - Contract error code
73
+ * @param {string} [source] - Contract that raised the error, when known
74
+ * @param {string} [dexContract] - DEX contract address, when known
75
+ * @return {Error|null} - Null for an unknown code of the DEX
76
+ * @private
77
+ */
78
+ function contractError(code, source, dexContract) {
79
+ const raisedByToken = source && dexContract ? source !== dexContract : !ContractErrors[code] && !!TokenErrors[code]
80
+ if (raisedByToken)
81
+ return tokenError(code, source)
82
+ const err = ContractErrors[code]
83
+ if (!err)
84
+ return null
85
+ const error = new Error(`Contract execution error: #${code} ${err.message}`)
86
+ error.code = code
87
+ return error
88
+ }
89
+
78
90
  /**
79
91
  * Locate the contract that raised the error in a simulation event log. The log lists events newest first and an error
80
92
  * is re-emitted by every frame it fails, so the oldest `error` event with the code is where it was raised (errors of
@@ -115,17 +127,134 @@ function tokenError(code, contract) {
115
127
  }
116
128
 
117
129
  /**
118
- * Handle the failure of a transaction applied on-chain
119
- * @param {contract.SentTransaction} sent
120
- * @throws {Error} - Error with the transaction `hash` and its result
130
+ * Transaction-related error
131
+ * @param {'ERROR'|'TRY_AGAIN_LATER'|'FAILED'|'TIMEOUT'} status - `ERROR`: rejected with a result code (`errorResult`
132
+ * of `sendTransaction`), `TRY_AGAIN_LATER`: not accepted for now (congestion, or another transaction of the account
133
+ * pending), `FAILED`: applied and failed, `TIMEOUT`: not seen before its time bounds expired
134
+ * @param {{hash?: string, result?: xdr.TransactionResult, resultCode?: string, events?: xdr.DiagnosticEvent[], contractId?: string}} [details] -
135
+ * Transaction hash, its result (or its result code, when known without the result), the diagnostic events of a failed
136
+ * call and the DEX contract address
137
+ * @return {Error} - Error with `status`, `hash`, `result` (Horizon-style transaction result code, e.g. `tx_bad_seq`),
138
+ * `opResult` (operation result code of `tx_failed`, e.g. `invoke_host_function_trapped`), and `code` (plus `tokenError`
139
+ * and `contract` for a token) when the diagnostic events name the contract error the call failed with
121
140
  * @internal
122
141
  */
123
- export function processTransactionErrors(sent) {
124
- const response = sent.getTransactionResponse
125
- if (response?.status !== 'FAILED')
126
- return
127
- const hash = sent.sendTransactionResponse?.hash
128
- const error = new Error(`Transaction ${hash} failed: ${JSON.stringify(response.resultXdr?.result, (key, value) => typeof value === 'bigint' ? value.toString() : value)}`)
142
+ export function transactionError(status, {hash, result, resultCode: knownCode, events, contractId} = {}) {
143
+ const resultCode = knownCode ?? (result?.result?.type ? snakeCase(result.result.type) : undefined)
144
+ const opResult = operationResultCode(result)
145
+ const cause = events?.length ? findEventError(events) : undefined
146
+ const causeError = cause ? contractError(cause.code, cause.contract, contractId) : null
147
+ let message
148
+ switch (status) {
149
+ case 'ERROR':
150
+ message = `Transaction ${hash} was not accepted by the network: ${resultCode ?? 'unknown result'}`
151
+ break
152
+ case 'TRY_AGAIN_LATER':
153
+ message = `Transaction ${hash} was not accepted by the network for now, try again later`
154
+ break
155
+ case 'FAILED':
156
+ message = `Transaction ${hash} failed: ${resultCode ?? 'unknown result'}${opResult ? ` (${opResult})` : ''}`
157
+ break
158
+ default:
159
+ message = `Transaction ${hash} was not confirmed before its time bounds expired`
160
+ }
161
+ if (causeError) {
162
+ message += `. ${causeError.message}`
163
+ }
164
+ const error = new Error(message)
165
+ error.status = status
129
166
  error.hash = hash
130
- throw error
167
+ if (resultCode) {
168
+ error.result = resultCode
169
+ }
170
+ if (opResult) {
171
+ error.opResult = opResult
172
+ }
173
+ if (causeError) {
174
+ error.code = causeError.code
175
+ if (causeError.tokenError) {
176
+ error.tokenError = true
177
+ if (causeError.contract) {
178
+ error.contract = causeError.contract
179
+ }
180
+ }
181
+ }
182
+ return error
183
+ }
184
+
185
+ /**
186
+ * Code of the first failed operation of a `tx_failed` result
187
+ * @param {xdr.TransactionResult} [result]
188
+ * @return {string|undefined} - Horizon-style code, e.g. `invoke_host_function_trapped`
189
+ * @private
190
+ */
191
+ function operationResultCode(result) {
192
+ if (result?.result?.type !== 'txFailed')
193
+ return undefined
194
+ for (const op of result.result.results || []) {
195
+ //an applied operation reports its own result code, an operation that could not run the outer code
196
+ const code = op.type === 'opInner' ? op.tr?.value?.type : op.type
197
+ if (code && !/Success$/.test(code))
198
+ return snakeCase(code)
199
+ }
200
+ return undefined
201
+ }
202
+
203
+ /**
204
+ * Contract error a failed call raised, from its diagnostic events (oldest first). An error is re-emitted by every frame
205
+ * it fails, so the last error event carries the code the call failed with and the oldest event with that code names the
206
+ * contract that raised it
207
+ * @param {xdr.DiagnosticEvent[]} events
208
+ * @return {{code: number, contract?: string}|undefined}
209
+ * @private
210
+ */
211
+ function findEventError(events) {
212
+ const errors = []
213
+ for (const event of events) {
214
+ const code = eventErrorCode(event)
215
+ if (code !== undefined) {
216
+ errors.push({code, contract: eventContract(event)})
217
+ }
218
+ }
219
+ if (!errors.length)
220
+ return undefined
221
+ const {code} = errors[errors.length - 1]
222
+ return {code, contract: errors.find(error => error.code === code && error.contract)?.contract}
223
+ }
224
+
225
+ /**
226
+ * Contract error code of an `error` diagnostic event
227
+ * @param {xdr.DiagnosticEvent} event
228
+ * @return {number|undefined}
229
+ * @private
230
+ */
231
+ function eventErrorCode(event) {
232
+ const topics = event?.event?.body?.value?.topics
233
+ if (!topics || topics.length < 2)
234
+ return undefined
235
+ const [name, value] = topics
236
+ if (name.type !== 'scvSymbol' || name.sym.toString() !== 'error')
237
+ return undefined
238
+ if (value.type !== 'scvError' || value.error.type !== 'sceContract')
239
+ return undefined
240
+ return value.error.contractCode
241
+ }
242
+
243
+ /**
244
+ * @param {xdr.DiagnosticEvent} event
245
+ * @return {string|undefined} - Address of the contract that emitted the event
246
+ * @private
247
+ */
248
+ function eventContract(event) {
249
+ const id = event.event.contractId
250
+ return id ? StrKey.encodeContract(id.toBytes()) : undefined
251
+ }
252
+
253
+ /**
254
+ * @param {string} name - XDR union arm name, e.g. `txBadSeq`
255
+ * @return {string} - Horizon-style code, e.g. `tx_bad_seq`
256
+ * @private
257
+ */
258
+ function snakeCase(name) {
259
+ return name.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase())
131
260
  }
package/src/index.d.ts CHANGED
@@ -363,7 +363,11 @@ export interface SubsidizeArguments {
363
363
  amount: bigint;
364
364
  }
365
365
 
366
- /** Smart contract client for trading with AXIS DEX */
366
+ /**
367
+ * Smart contract client for trading with AXIS DEX. Calls submitting a transaction sign it with the wallet callback, then
368
+ * send it over RPC and wait for its result: a transaction the network does not accept, that fails on-chain or that is
369
+ * not confirmed in time throws a `TransactionError`
370
+ */
367
371
  export declare class AxisContractClient {
368
372
  constructor(params: ClientInitializationParams);
369
373
 
@@ -1079,7 +1083,13 @@ export declare function invertTicker(entry: TickerEntry): TickerEntry;
1079
1083
  */
1080
1084
  export declare function parseApiDate(value: string | number | undefined): number;
1081
1085
 
1082
- /** Default allowance lifetime granted with a trade, in ledgers: ~180 days at 5s per ledger (the maximum entry TTL) */
1086
+ /**
1087
+ * Longest allowance lifetime the client grants, in ledgers: ~180 days at 5s per ledger, one hour (720 ledgers) short of
1088
+ * the network maximum entry TTL, since the token rejects a lifetime beyond the maximum of the ledger it applies in while
1089
+ * the client counts from the ledger pushed by the AXIS API (3,109,680)
1090
+ */
1091
+ export declare const MAX_APPROVAL_TTL_LEDGERS: number;
1092
+ /** Default allowance lifetime granted with a trade, in ledgers (`MAX_APPROVAL_TTL_LEDGERS`, ~180 days) */
1083
1093
  export declare const APPROVAL_TTL_LEDGERS: number;
1084
1094
  /** An allowance expiring within this number of ledgers is renewed with the next trade (~1 day) */
1085
1095
  export declare const APPROVAL_RENEW_LEDGERS: number;
@@ -1095,7 +1105,7 @@ export interface ApprovalPlanParams {
1095
1105
  ledger: number;
1096
1106
  /** Ledger the current allowance lives until (0 or omitted when unknown) */
1097
1107
  liveUntil?: number;
1098
- /** Lifetime of a new allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default */
1108
+ /** Lifetime of a new allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS` */
1099
1109
  ttl?: number;
1100
1110
  }
1101
1111
 
@@ -1107,6 +1117,27 @@ export interface ApprovalPlanParams {
1107
1117
  */
1108
1118
  export declare function planApproval(params: ApprovalPlanParams): {amount: bigint, liveUntil: number} | undefined;
1109
1119
 
1120
+ export interface ReductionPlanParams {
1121
+ /** Amount the open orders selling the asset still need after the call */
1122
+ target: bigint;
1123
+ /** Current allowance */
1124
+ allowance: bigint;
1125
+ /** Current ledger sequence */
1126
+ ledger: number;
1127
+ /** Ledger the current allowance lives until (0 or omitted when unknown) */
1128
+ liveUntil?: number;
1129
+ /** Lifetime of a renewed allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS` */
1130
+ ttl?: number;
1131
+ }
1132
+
1133
+ /**
1134
+ * Decide whether the allowance can be lowered once the open orders selling the token need less of it (orders canceled
1135
+ * or shrunk). A zero target revokes the allowance (`liveUntil` 0). A nonzero one keeps the current lifetime when it lasts
1136
+ * more than `APPROVAL_RENEW_LEDGERS`, and renews it otherwise. An expired allowance is left alone
1137
+ * @returns Approval to pass with the call, undefined when the allowance does not exceed the target
1138
+ */
1139
+ export declare function planReduction(params: ReductionPlanParams): {amount: bigint, liveUntil: number} | undefined;
1140
+
1110
1141
  /**
1111
1142
  * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`
1112
1143
  * @param amount - Amount of `buying` tokens to acquire
@@ -1529,18 +1560,24 @@ export type AccountMarketFilter = string | {base: string, quote: string} | strin
1529
1560
  * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
1530
1561
  * - `order` `{action, order, fill?}` - any order change
1531
1562
  * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
1532
- * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
1563
+ * - `approve` `{asset, amount, liveUntil}` - a call is about to set an allowance (grant, renew, lower or revoke it)
1533
1564
  * - `trade` {ApiTrade} - the account performed a trade
1534
1565
  * - `swap` {ApiSwap} - the account performed a swap
1535
1566
  * - `change` - the open orders or the backing changed
1536
1567
  * - `error` `Error` - the push API rejected the account subscription
1568
+ *
1569
+ * Calls submitting transactions (`sell`, `buy`, `swap`, `update`, `cancel`, `cancelAll`, `revoke`, `crossfill`) run one
1570
+ * at a time: each one builds its transaction and plans its approvals after the previous one settled.
1537
1571
  */
1538
1572
  export declare class AxisAccount extends Emitter {
1539
1573
  /** Trader address */
1540
1574
  readonly address: string;
1541
1575
  /** Wallet signing callback, required to trade */
1542
1576
  signTransaction?: SignTransactionCallback;
1543
- /** Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default) */
1577
+ /**
1578
+ * Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default, at most
1579
+ * `MAX_APPROVAL_TTL_LEDGERS`)
1580
+ */
1544
1581
  approvalTtl: number;
1545
1582
  /** Open orders by id */
1546
1583
  readonly orders: Map<string, AccountOrder>;
@@ -1602,17 +1639,27 @@ export declare class AxisAccount extends Emitter {
1602
1639
  */
1603
1640
  estimateBuy(params: AccountTradeParams): Promise<TradeEstimate>;
1604
1641
  /**
1605
- * Change the amount, price or expiration of open orders (omitted fields keep their current values)
1642
+ * Change the amount, price or expiration of open orders (omitted fields keep their current values). The allowance of
1643
+ * every sold token follows what its open orders need: raised when they grow, or when it does not back the changed
1644
+ * orders, lowered when they shrink
1606
1645
  * @returns Updated order ids
1607
1646
  */
1608
1647
  update(updates: Array<{id: bigint | string, amount?: bigint, price?: bigint, expires?: number}>): Promise<bigint[]>;
1609
- /** Cancel open orders */
1648
+ /** Cancel open orders, lowering the allowance of every sold token to what its remaining open orders need */
1610
1649
  cancel(ids: Array<bigint | string>): Promise<void>;
1611
1650
  /**
1612
- * Cancel all open orders
1651
+ * Cancel all open orders, lowering the allowances like `cancel`
1613
1652
  * @returns Canceled order ids
1614
1653
  */
1615
1654
  cancelAll(filter?: {market?: AccountMarketFilter}): Promise<string[]>;
1655
+ /**
1656
+ * Set the allowances granted to the AXIS contract on tokens to zero, optionally canceling the open orders selling
1657
+ * them in the same transactions. The revocation goes with the first transaction. Works while the contract is frozen
1658
+ * @param assets - Token contract ids
1659
+ * @param options - `cancelOrders`: also cancel every open order selling these tokens
1660
+ * @throws The submission error, with the `revoked` tokens and the `canceled` order ids done before it
1661
+ */
1662
+ revoke(assets: string[], options?: {cancelOrders?: boolean}): Promise<AccountRevokeResult>;
1616
1663
  /**
1617
1664
  * Fill an open order against the book while keeping profits from price inefficiencies
1618
1665
  * @param takerOrderId - Order acting as the taker
@@ -1633,5 +1680,42 @@ export declare class AxisAccount extends Emitter {
1633
1680
  close(): void;
1634
1681
  }
1635
1682
 
1683
+ /** Result of `AxisAccount.revoke` */
1684
+ export interface AccountRevokeResult {
1685
+ /** Tokens whose allowance was set to zero */
1686
+ revoked: string[];
1687
+ /** Canceled order ids */
1688
+ canceled: string[];
1689
+ }
1690
+
1691
+ /**
1692
+ * Error thrown when a submitted transaction is not accepted by the network, fails on-chain or is not confirmed in time
1693
+ * (a plain `Error` with these properties)
1694
+ */
1695
+ export interface TransactionError extends Error {
1696
+ /**
1697
+ * - `ERROR`: rejected with a result code (`result`)
1698
+ * - `TRY_AGAIN_LATER`: not accepted for now, the network is congested or another transaction of the account is pending
1699
+ * - `FAILED`: applied and failed on-chain
1700
+ * - `TIMEOUT`: not seen before its time bounds expired, it can no longer be included
1701
+ */
1702
+ status: 'ERROR' | 'TRY_AGAIN_LATER' | 'FAILED' | 'TIMEOUT';
1703
+ /** Transaction hash, hex */
1704
+ hash: string;
1705
+ /** Transaction result code, Horizon style (`tx_bad_seq`, `tx_insufficient_fee`, `tx_failed`...) */
1706
+ result?: string;
1707
+ /** Result code of the failed operation of `tx_failed` (`invoke_host_function_trapped`...) */
1708
+ opResult?: string;
1709
+ /**
1710
+ * Contract error code the call failed with, when the RPC server returns the diagnostic events of the transaction:
1711
+ * a DEX error (see `ContractErrors`), or a token error with `tokenError` set
1712
+ */
1713
+ code?: number;
1714
+ /** The error was raised by a token transfer */
1715
+ tokenError?: boolean;
1716
+ /** Token contract that raised the error */
1717
+ contract?: string;
1718
+ }
1719
+
1636
1720
  /** Convert an API order to the client form (bigint amounts and prices, numeric timestamps) */
1637
1721
  export declare function parseApiOrder(raw: ApiOrder): AccountOrder;
package/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import {Contract, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'
1
+ import {Contract, Keypair, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'
2
2
  import ContractClient from './contract-client.js'
3
- import {ContractErrors, TokenErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
3
+ import {ContractErrors, TokenErrors, processSimulationErrors, transactionError} from './errors.js'
4
4
  import {AxisApiClient, AxisApiError} from './api-client.js'
5
5
  import {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'
6
6
  import {orderId, generateNonce} from './order-id.js'
@@ -13,7 +13,7 @@ export {AxisAccount, parseApiOrder} from './axis-account.js'
13
13
  export {AxisStreamClient} from './stream-client.js'
14
14
  export {TokenBalance} from './token-balance.js'
15
15
  export {Emitter} from './emitter.js'
16
- export {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'
16
+ export {planApproval, planReduction, maxQuoteSpend, APPROVAL_TTL_LEDGERS, MAX_APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'
17
17
  export {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'
18
18
  export {parseApiDate} from './api-dates.js'
19
19
 
@@ -24,6 +24,21 @@ const DEFAULT_LEDGER_TIME = 5
24
24
  const KEEPALIVE_DAYS = 30
25
25
  //validity window of transactions built by the client, in seconds
26
26
  const TX_TIMEOUT = 60
27
+ //delay between transaction status checks: grows by 1 s per check, up to 3 s
28
+ const POLL_STEP = 1_000
29
+ const POLL_MAX_DELAY = 3_000
30
+ //how long to look for a transaction whose submission request failed, in milliseconds
31
+ const SEND_FAILURE_WINDOW = 30_000
32
+ //failed status requests in a row after which a transaction whose submission request failed is reported as not sent
33
+ const SEND_FAILURE_REQUESTS = 3
34
+ //margin for the local clock when the RPC server reports no ledger close time, in seconds
35
+ const CLOCK_MARGIN = 15
36
+ //how long to wait for a transaction without time bounds, in milliseconds
37
+ const UNBOUNDED_WAIT = 300_000
38
+ //status checks after which a transaction not found yet is checked against the sequence number of its source account
39
+ const SEQUENCE_CHECK_AFTER = 3
40
+ //a pending transaction another transaction of the account replaced: dropped by the network
41
+ const SUPERSEDED = Symbol('superseded')
27
42
 
28
43
  /**
29
44
  * Smart contract client for trading with AXIS DEX
@@ -406,23 +421,160 @@ function isArchived(entry, latestLedger) {
406
421
  /**
407
422
  * Submit a signed transaction and wait for its result
408
423
  * @param {rpc.Server} server
424
+ * @param {import('@stellar/stellar-sdk').Transaction} tx - Signed transaction
425
+ * @param {string} [contractId] - DEX contract address, to tell its errors from the errors of the tokens it calls
426
+ * @return {Promise<rpc.Api.GetSuccessfulTransactionResponse>}
427
+ * @throws {Error} - A {@link transactionError} when the network does not accept the transaction (`ERROR`,
428
+ * `TRY_AGAIN_LATER`), it fails on-chain (`FAILED`) or it is not seen before its time bounds expire (`TIMEOUT`); the
429
+ * request error, with the transaction `hash`, when the RPC server cannot be reached
430
+ * @internal
431
+ */
432
+ async function submitTransaction(server, tx, contractId) {
433
+ const hash = toHex(tx.hash())
434
+ let sent
435
+ try {
436
+ sent = await server.sendTransaction(tx)
437
+ } catch (e) {
438
+ //the request may have reached the network before it failed: look for the transaction before reporting it
439
+ const response = await waitForTransaction(server, tx, hash, {window: SEND_FAILURE_WINDOW, maxFailures: SEND_FAILURE_REQUESTS})
440
+ if (!response) {
441
+ if (e instanceof Error) {
442
+ e.hash = hash
443
+ }
444
+ throw e
445
+ }
446
+ return checkTransaction(response, hash, contractId)
447
+ }
448
+ if (sent.status === 'ERROR')
449
+ throw transactionError('ERROR', {hash, result: sent.errorResult, events: sent.diagnosticEvents, contractId})
450
+ if (sent.status === 'TRY_AGAIN_LATER')
451
+ throw transactionError('TRY_AGAIN_LATER', {hash})
452
+ //PENDING, or DUPLICATE when the network already has it
453
+ const response = await waitForTransaction(server, tx, hash)
454
+ if (!response)
455
+ throw transactionError('TIMEOUT', {hash})
456
+ return checkTransaction(response, hash, contractId)
457
+ }
458
+
459
+ /**
460
+ * Poll the status of a submitted transaction until it is found, or can no longer be included: its time bounds expired,
461
+ * or another transaction of its source account consumed its sequence number (an RPC server behind a load balancer can
462
+ * accept two transactions with the same sequence number, the network then drops one of them)
463
+ * @param {rpc.Server} server
464
+ * @param {import('@stellar/stellar-sdk').Transaction} tx - Submitted transaction
465
+ * @param {string} hash - Transaction hash, hex
466
+ * @param {{window?: number, maxFailures?: number}} [options] - Longest wait in milliseconds, and the number of failed
467
+ * requests in a row to give up after
468
+ * @return {Promise<rpc.Api.GetSuccessfulTransactionResponse|rpc.Api.GetFailedTransactionResponse|SUPERSEDED|undefined>} -
469
+ * Undefined if not found
470
+ * @internal
471
+ */
472
+ async function waitForTransaction(server, tx, hash, {window, maxFailures} = {}) {
473
+ const started = Date.now()
474
+ const maxTime = Number(tx.timeBounds?.maxTime) || 0
475
+ let failures = 0
476
+ let consumedAt
477
+ for (let attempt = 1; ; attempt++) {
478
+ let response
479
+ try {
480
+ response = await server.getTransaction(hash)
481
+ failures = 0
482
+ } catch (e) {
483
+ failures++ //a failed request tells nothing about the transaction
484
+ }
485
+ if (response && response.status !== 'NOT_FOUND')
486
+ return response
487
+ //the server had seen the ledger where the sequence number was consumed and still does not know the transaction
488
+ if (consumedAt !== undefined && response?.latestLedger >= consumedAt)
489
+ return SUPERSEDED
490
+ if (consumedAt === undefined && response && attempt >= SEQUENCE_CHECK_AFTER) {
491
+ consumedAt = await sequenceConsumedAt(server, tx)
492
+ }
493
+ if (maxFailures && failures >= maxFailures)
494
+ return undefined
495
+ if (window && Date.now() - started >= window)
496
+ return undefined
497
+ if (isPastTimeBounds(response, maxTime, started))
498
+ return undefined
499
+ await new Promise(resolve => setTimeout(resolve, Math.min(attempt * POLL_STEP, POLL_MAX_DELAY)))
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Check whether the source account of a transaction moved past its sequence number
505
+ * @param {rpc.Server} server
409
506
  * @param {import('@stellar/stellar-sdk').Transaction} tx
410
- * @return {Promise<void>}
411
- * @throws {Error} - If the transaction is rejected, fails or is not included in time
507
+ * @return {Promise<number|undefined>} - Latest ledger of the RPC server when it reported the account past the
508
+ * transaction sequence number, undefined otherwise
412
509
  * @internal
413
510
  */
414
- async function submitTransaction(server, tx) {
415
- const sent = await server.sendTransaction(tx)
416
- if (sent.status !== 'PENDING' && sent.status !== 'DUPLICATE')
417
- throw new Error(`Transaction ${sent.hash} rejected: ${sent.errorResult?.result?.type ?? sent.status}`)
418
- const res = await server.pollTransaction(sent.hash, {attempts: TX_TIMEOUT})
419
- if (res.status === 'FAILED') {
420
- const error = new Error(`Transaction ${sent.hash} failed: ${res.resultXdr?.result?.type ?? 'unknown result'}`)
421
- error.hash = sent.hash
422
- throw error
511
+ async function sequenceConsumedAt(server, tx) {
512
+ try {
513
+ const key = xdr.LedgerKey.account(new xdr.LedgerKeyAccount({accountId: Keypair.fromPublicKey(tx.source).xdrPublicKey()}))
514
+ const {entries, latestLedger} = await server.getLedgerEntries(key)
515
+ const seqNum = entries[0]?.val?.value?.seqNum
516
+ return seqNum !== undefined && BigInt(seqNum) >= BigInt(tx.sequence) ? latestLedger : undefined
517
+ } catch (e) {
518
+ return undefined //a muxed source, or the request failed
423
519
  }
424
- if (res.status !== 'SUCCESS')
425
- throw new Error(`Transaction ${sent.hash} was not included in time`)
520
+ }
521
+
522
+ /**
523
+ * Whether a transaction not found yet can no longer be included: a ledger closing after its upper time bound cannot
524
+ * include it, and the RPC server has seen every ledger up to the latest one it reports
525
+ * @param {rpc.Api.GetTransactionResponse|undefined} response - Latest status response, if any
526
+ * @param {number} maxTime - Upper time bound, UNIX seconds (0 = none)
527
+ * @param {number} started - When polling started, UNIX milliseconds
528
+ * @return {boolean}
529
+ * @internal
530
+ */
531
+ function isPastTimeBounds(response, maxTime, started) {
532
+ if (!maxTime)
533
+ return Date.now() - started >= UNBOUNDED_WAIT
534
+ const closeTime = Number(response?.latestLedgerCloseTime)
535
+ if (closeTime)
536
+ return closeTime > maxTime
537
+ return Date.now() / 1000 > maxTime + CLOCK_MARGIN
538
+ }
539
+
540
+ /**
541
+ * @param {rpc.Api.GetSuccessfulTransactionResponse|rpc.Api.GetFailedTransactionResponse|SUPERSEDED} response
542
+ * @param {string} hash
543
+ * @param {string} [contractId]
544
+ * @return {rpc.Api.GetSuccessfulTransactionResponse}
545
+ * @throws {Error} - A `FAILED` {@link transactionError}, or an `ERROR` one with `tx_bad_seq` for a transaction dropped
546
+ * because another one consumed its sequence number
547
+ * @internal
548
+ */
549
+ function checkTransaction(response, hash, contractId) {
550
+ if (response === SUPERSEDED)
551
+ throw transactionError('ERROR', {hash, resultCode: 'tx_bad_seq'})
552
+ if (response.status === 'FAILED')
553
+ throw transactionError('FAILED', {hash, result: response.resultXdr, events: diagnosticEvents(response), contractId})
554
+ return response
555
+ }
556
+
557
+ /**
558
+ * Diagnostic events of an applied transaction: reported separately by RPC servers that keep them, otherwise taken from
559
+ * the transaction meta (empty when the network did not record them)
560
+ * @param {rpc.Api.GetFailedTransactionResponse} response
561
+ * @return {xdr.DiagnosticEvent[]}
562
+ * @internal
563
+ */
564
+ function diagnosticEvents(response) {
565
+ if (response.diagnosticEventsXdr?.length)
566
+ return response.diagnosticEventsXdr
567
+ const meta = response.resultMetaXdr?.value
568
+ return meta?.diagnosticEvents ?? meta?.sorobanMeta?.diagnosticEvents ?? []
569
+ }
570
+
571
+ /**
572
+ * @param {Uint8Array} bytes
573
+ * @return {string}
574
+ * @internal
575
+ */
576
+ function toHex(bytes) {
577
+ return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
426
578
  }
427
579
 
428
580
  /**
@@ -439,16 +591,18 @@ function toApproval(approve, defaultAsset) {
439
591
  }
440
592
 
441
593
  /**
442
- * Sign and submit a simulated transaction
594
+ * Sign and submit a simulated transaction. Submitted over RPC directly rather than with `tx.signAndSend()`, whose send
595
+ * failure carries the RPC response only as text
443
596
  * @param {contract.AssembledTransaction} tx
444
597
  * @return {Promise<*>} - Parsed contract call result
445
- * @throws {Error} - If the transaction failed on-chain
598
+ * @throws {Error} - The wallet error when signing fails, a {@link transactionError} when the transaction is not
599
+ * accepted, fails on-chain or is not confirmed in time
446
600
  * @internal
447
601
  */
448
602
  async function signAndSend(tx) {
449
- const sent = await tx.signAndSend()
450
- processTransactionErrors(sent)
451
- return sent.result
603
+ await tx.sign()
604
+ const response = await submitTransaction(tx.server, tx.signed, tx.options.contractId)
605
+ return response.returnValue === undefined ? undefined : tx.options.parseResultXdr(response.returnValue)
452
606
  }
453
607
 
454
608
  async function execTrade(params, direction, context) {