@axis-markets/client 0.8.3 → 0.9.1
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/README.md +684 -660
- package/lib/axis-client.cjs +1 -1
- package/lib/axis-client.cjs.map +1 -1
- package/package.json +1 -1
- package/src/allowance.js +78 -47
- package/src/api-client.js +18 -3
- package/src/axis-account.js +439 -85
- package/src/errors.js +150 -21
- package/src/index.d.ts +116 -10
- package/src/index.js +175 -21
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
|
|
63
|
-
|
|
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
|
-
*
|
|
119
|
-
* @param {
|
|
120
|
-
*
|
|
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
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
|
|
@@ -529,9 +533,9 @@ export interface QuotePathStep {
|
|
|
529
533
|
selling: string;
|
|
530
534
|
/** Buying asset contract id at this hop */
|
|
531
535
|
buying: string;
|
|
532
|
-
/** Maker order IDs
|
|
536
|
+
/** Maker order IDs to pass to the contract: the orders the quote fills, followed on a direct route by spare orders the contract reaches only when it passes over one of them (at most 19 in all) */
|
|
533
537
|
orders: string[];
|
|
534
|
-
/** Highest price among the
|
|
538
|
+
/** Highest price among the orders the quote fills (maker `buying` per `selling`, 18 decimals): a trade limit at this price crosses them all. Spares are priced at or below it, except in a `maxPrice` crossing, where they reach up to `maxPrice` */
|
|
535
539
|
worstPrice?: string;
|
|
536
540
|
}
|
|
537
541
|
|
|
@@ -683,16 +687,38 @@ export interface ContractInfoMarket {
|
|
|
683
687
|
refreshed: string;
|
|
684
688
|
}
|
|
685
689
|
|
|
690
|
+
/** Market token metadata (only `contract` until the AXIS API resolves it) */
|
|
691
|
+
export interface ContractInfoAsset {
|
|
692
|
+
/** Token contract address */
|
|
693
|
+
contract: string;
|
|
694
|
+
/** Asset code (token symbol) */
|
|
695
|
+
code?: string;
|
|
696
|
+
/** Issuer account of a classic asset, `native` for XLM, absent for a SEP-41 token */
|
|
697
|
+
issuer?: string;
|
|
698
|
+
/** Token decimals */
|
|
699
|
+
decimals?: number;
|
|
700
|
+
/** Asset name */
|
|
701
|
+
name?: string;
|
|
702
|
+
/** Home domain of the issuer */
|
|
703
|
+
domain?: string;
|
|
704
|
+
/** Icon URL */
|
|
705
|
+
icon?: string;
|
|
706
|
+
}
|
|
707
|
+
|
|
686
708
|
/** Contract state tracked by the indexer */
|
|
687
709
|
export interface ContractInfo {
|
|
688
710
|
/** AXIS contract address */
|
|
689
711
|
address: string;
|
|
712
|
+
/** Stellar network of the contract */
|
|
713
|
+
network?: 'mainnet' | 'testnet';
|
|
690
714
|
/** Whether trading is blocked by the safety admin */
|
|
691
715
|
frozen: boolean;
|
|
692
716
|
/** Contract configuration */
|
|
693
717
|
config?: ContractInfoConfig;
|
|
694
718
|
/** Markets opened by `subsidize` */
|
|
695
719
|
markets: ContractInfoMarket[];
|
|
720
|
+
/** Metadata of the market tokens */
|
|
721
|
+
assets?: ContractInfoAsset[];
|
|
696
722
|
}
|
|
697
723
|
|
|
698
724
|
export interface OrdersParams {
|
|
@@ -1079,7 +1105,13 @@ export declare function invertTicker(entry: TickerEntry): TickerEntry;
|
|
|
1079
1105
|
*/
|
|
1080
1106
|
export declare function parseApiDate(value: string | number | undefined): number;
|
|
1081
1107
|
|
|
1082
|
-
/**
|
|
1108
|
+
/**
|
|
1109
|
+
* Longest allowance lifetime the client grants, in ledgers: ~180 days at 5s per ledger, one hour (720 ledgers) short of
|
|
1110
|
+
* the network maximum entry TTL, since the token rejects a lifetime beyond the maximum of the ledger it applies in while
|
|
1111
|
+
* the client counts from the ledger pushed by the AXIS API (3,109,680)
|
|
1112
|
+
*/
|
|
1113
|
+
export declare const MAX_APPROVAL_TTL_LEDGERS: number;
|
|
1114
|
+
/** Default allowance lifetime granted with a trade, in ledgers (`MAX_APPROVAL_TTL_LEDGERS`, ~180 days) */
|
|
1083
1115
|
export declare const APPROVAL_TTL_LEDGERS: number;
|
|
1084
1116
|
/** An allowance expiring within this number of ledgers is renewed with the next trade (~1 day) */
|
|
1085
1117
|
export declare const APPROVAL_RENEW_LEDGERS: number;
|
|
@@ -1095,7 +1127,7 @@ export interface ApprovalPlanParams {
|
|
|
1095
1127
|
ledger: number;
|
|
1096
1128
|
/** Ledger the current allowance lives until (0 or omitted when unknown) */
|
|
1097
1129
|
liveUntil?: number;
|
|
1098
|
-
/** Lifetime of a new allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default */
|
|
1130
|
+
/** Lifetime of a new allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS` */
|
|
1099
1131
|
ttl?: number;
|
|
1100
1132
|
}
|
|
1101
1133
|
|
|
@@ -1107,6 +1139,27 @@ export interface ApprovalPlanParams {
|
|
|
1107
1139
|
*/
|
|
1108
1140
|
export declare function planApproval(params: ApprovalPlanParams): {amount: bigint, liveUntil: number} | undefined;
|
|
1109
1141
|
|
|
1142
|
+
export interface ReductionPlanParams {
|
|
1143
|
+
/** Amount the open orders selling the asset still need after the call */
|
|
1144
|
+
target: bigint;
|
|
1145
|
+
/** Current allowance */
|
|
1146
|
+
allowance: bigint;
|
|
1147
|
+
/** Current ledger sequence */
|
|
1148
|
+
ledger: number;
|
|
1149
|
+
/** Ledger the current allowance lives until (0 or omitted when unknown) */
|
|
1150
|
+
liveUntil?: number;
|
|
1151
|
+
/** Lifetime of a renewed allowance in ledgers, `APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS` */
|
|
1152
|
+
ttl?: number;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/**
|
|
1156
|
+
* Decide whether the allowance can be lowered once the open orders selling the token need less of it (orders canceled
|
|
1157
|
+
* or shrunk). A zero target revokes the allowance (`liveUntil` 0). A nonzero one keeps the current lifetime when it lasts
|
|
1158
|
+
* more than `APPROVAL_RENEW_LEDGERS`, and renews it otherwise. An expired allowance is left alone
|
|
1159
|
+
* @returns Approval to pass with the call, undefined when the allowance does not exceed the target
|
|
1160
|
+
*/
|
|
1161
|
+
export declare function planReduction(params: ReductionPlanParams): {amount: bigint, liveUntil: number} | undefined;
|
|
1162
|
+
|
|
1110
1163
|
/**
|
|
1111
1164
|
* Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`
|
|
1112
1165
|
* @param amount - Amount of `buying` tokens to acquire
|
|
@@ -1529,18 +1582,24 @@ export type AccountMarketFilter = string | {base: string, quote: string} | strin
|
|
|
1529
1582
|
* - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
|
|
1530
1583
|
* - `order` `{action, order, fill?}` - any order change
|
|
1531
1584
|
* - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
|
|
1532
|
-
* - `approve` `{asset, amount, liveUntil}` - a
|
|
1585
|
+
* - `approve` `{asset, amount, liveUntil}` - a call is about to set an allowance (grant, renew, lower or revoke it)
|
|
1533
1586
|
* - `trade` {ApiTrade} - the account performed a trade
|
|
1534
1587
|
* - `swap` {ApiSwap} - the account performed a swap
|
|
1535
1588
|
* - `change` - the open orders or the backing changed
|
|
1536
1589
|
* - `error` `Error` - the push API rejected the account subscription
|
|
1590
|
+
*
|
|
1591
|
+
* Calls submitting transactions (`sell`, `buy`, `swap`, `update`, `cancel`, `cancelAll`, `revoke`, `crossfill`) run one
|
|
1592
|
+
* at a time: each one builds its transaction and plans its approvals after the previous one settled.
|
|
1537
1593
|
*/
|
|
1538
1594
|
export declare class AxisAccount extends Emitter {
|
|
1539
1595
|
/** Trader address */
|
|
1540
1596
|
readonly address: string;
|
|
1541
1597
|
/** Wallet signing callback, required to trade */
|
|
1542
1598
|
signTransaction?: SignTransactionCallback;
|
|
1543
|
-
/**
|
|
1599
|
+
/**
|
|
1600
|
+
* Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default, at most
|
|
1601
|
+
* `MAX_APPROVAL_TTL_LEDGERS`)
|
|
1602
|
+
*/
|
|
1544
1603
|
approvalTtl: number;
|
|
1545
1604
|
/** Open orders by id */
|
|
1546
1605
|
readonly orders: Map<string, AccountOrder>;
|
|
@@ -1602,17 +1661,27 @@ export declare class AxisAccount extends Emitter {
|
|
|
1602
1661
|
*/
|
|
1603
1662
|
estimateBuy(params: AccountTradeParams): Promise<TradeEstimate>;
|
|
1604
1663
|
/**
|
|
1605
|
-
* Change the amount, price or expiration of open orders (omitted fields keep their current values)
|
|
1664
|
+
* Change the amount, price or expiration of open orders (omitted fields keep their current values). The allowance of
|
|
1665
|
+
* every sold token follows what its open orders need: raised when they grow, or when it does not back the changed
|
|
1666
|
+
* orders, lowered when they shrink
|
|
1606
1667
|
* @returns Updated order ids
|
|
1607
1668
|
*/
|
|
1608
1669
|
update(updates: Array<{id: bigint | string, amount?: bigint, price?: bigint, expires?: number}>): Promise<bigint[]>;
|
|
1609
|
-
/** Cancel open orders */
|
|
1670
|
+
/** Cancel open orders, lowering the allowance of every sold token to what its remaining open orders need */
|
|
1610
1671
|
cancel(ids: Array<bigint | string>): Promise<void>;
|
|
1611
1672
|
/**
|
|
1612
|
-
* Cancel all open orders
|
|
1673
|
+
* Cancel all open orders, lowering the allowances like `cancel`
|
|
1613
1674
|
* @returns Canceled order ids
|
|
1614
1675
|
*/
|
|
1615
1676
|
cancelAll(filter?: {market?: AccountMarketFilter}): Promise<string[]>;
|
|
1677
|
+
/**
|
|
1678
|
+
* Set the allowances granted to the AXIS contract on tokens to zero, optionally canceling the open orders selling
|
|
1679
|
+
* them in the same transactions. The revocation goes with the first transaction. Works while the contract is frozen
|
|
1680
|
+
* @param assets - Token contract ids
|
|
1681
|
+
* @param options - `cancelOrders`: also cancel every open order selling these tokens
|
|
1682
|
+
* @throws The submission error, with the `revoked` tokens and the `canceled` order ids done before it
|
|
1683
|
+
*/
|
|
1684
|
+
revoke(assets: string[], options?: {cancelOrders?: boolean}): Promise<AccountRevokeResult>;
|
|
1616
1685
|
/**
|
|
1617
1686
|
* Fill an open order against the book while keeping profits from price inefficiencies
|
|
1618
1687
|
* @param takerOrderId - Order acting as the taker
|
|
@@ -1633,5 +1702,42 @@ export declare class AxisAccount extends Emitter {
|
|
|
1633
1702
|
close(): void;
|
|
1634
1703
|
}
|
|
1635
1704
|
|
|
1705
|
+
/** Result of `AxisAccount.revoke` */
|
|
1706
|
+
export interface AccountRevokeResult {
|
|
1707
|
+
/** Tokens whose allowance was set to zero */
|
|
1708
|
+
revoked: string[];
|
|
1709
|
+
/** Canceled order ids */
|
|
1710
|
+
canceled: string[];
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
/**
|
|
1714
|
+
* Error thrown when a submitted transaction is not accepted by the network, fails on-chain or is not confirmed in time
|
|
1715
|
+
* (a plain `Error` with these properties)
|
|
1716
|
+
*/
|
|
1717
|
+
export interface TransactionError extends Error {
|
|
1718
|
+
/**
|
|
1719
|
+
* - `ERROR`: rejected with a result code (`result`)
|
|
1720
|
+
* - `TRY_AGAIN_LATER`: not accepted for now, the network is congested or another transaction of the account is pending
|
|
1721
|
+
* - `FAILED`: applied and failed on-chain
|
|
1722
|
+
* - `TIMEOUT`: not seen before its time bounds expired, it can no longer be included
|
|
1723
|
+
*/
|
|
1724
|
+
status: 'ERROR' | 'TRY_AGAIN_LATER' | 'FAILED' | 'TIMEOUT';
|
|
1725
|
+
/** Transaction hash, hex */
|
|
1726
|
+
hash: string;
|
|
1727
|
+
/** Transaction result code, Horizon style (`tx_bad_seq`, `tx_insufficient_fee`, `tx_failed`...) */
|
|
1728
|
+
result?: string;
|
|
1729
|
+
/** Result code of the failed operation of `tx_failed` (`invoke_host_function_trapped`...) */
|
|
1730
|
+
opResult?: string;
|
|
1731
|
+
/**
|
|
1732
|
+
* Contract error code the call failed with, when the RPC server returns the diagnostic events of the transaction:
|
|
1733
|
+
* a DEX error (see `ContractErrors`), or a token error with `tokenError` set
|
|
1734
|
+
*/
|
|
1735
|
+
code?: number;
|
|
1736
|
+
/** The error was raised by a token transfer */
|
|
1737
|
+
tokenError?: boolean;
|
|
1738
|
+
/** Token contract that raised the error */
|
|
1739
|
+
contract?: string;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1636
1742
|
/** Convert an API order to the client form (bigint amounts and prices, numeric timestamps) */
|
|
1637
1743
|
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,
|
|
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<
|
|
411
|
-
*
|
|
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
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
|
|
425
|
-
|
|
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} -
|
|
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
|
-
|
|
450
|
-
|
|
451
|
-
return
|
|
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) {
|