@axis-markets/client 0.8.2 → 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/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) {