@axis-markets/client 0.7.0 → 0.8.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,522 +1,717 @@
1
- import {Networks, contract, rpc} from '@stellar/stellar-sdk'
2
- import ContractClient from './contract-client.js'
3
- import {ContractErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
4
- import {AxisApiClient, AxisApiError} from './api-client.js'
5
- import {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'
6
- import {orderId, generateNonce} from './order-id.js'
7
- import {OrderKind, TradeDirection} from './constants.js'
8
-
9
- export {ContractErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}
10
- export {Axis, toWsUrl} from './axis.js'
11
- export {AxisMarket} from './axis-market.js'
12
- export {AxisAccount, parseApiOrder} from './axis-account.js'
13
- export {AxisStreamClient} from './stream-client.js'
14
- export {TokenBalance} from './token-balance.js'
15
- export {Emitter} from './emitter.js'
16
- export {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'
17
- export {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'
18
- export {parseApiDate} from './api-dates.js'
19
-
20
- /**
21
- * Smart contract client for trading with AXIS DEX
22
- */
23
- export class AxisContractClient {
24
- /**
25
- * @param {ClientInitializationParams} params
26
- */
27
- constructor(params) {
28
- const options = {
29
- publicKey: params.publicKey,
30
- signTransaction: params.signTransaction,
31
- rpcUrl: params.rpcUrl,
32
- allowHttp: true,
33
- networkPassphrase: params.networkPassphrase || Networks.PUBLIC,
34
- contractId: params.contractId
35
- }
36
- this.client = new ContractClient(options)
37
- this.fee = params.fee || '100000'
38
- this.autoFootprint = params.autoFootprint !== false
39
- this.server = new rpc.Server(params.rpcUrl, {allowHttp: true})
40
- this.assetCache = new Map()
41
- }
42
-
43
- /**
44
- * Account that signs and pays for the transactions
45
- * @return {string}
46
- */
47
- get publicKey() {
48
- return this.client.options.publicKey
49
- }
50
-
51
- /**
52
- * Fetch existing order.
53
- * @param {bigint} id - ID of the order to fetch
54
- * @return {Promise<Order|undefined>} - Order fetched from the storage, undefined if not found or expired
55
- */
56
- async order(id) {
57
- const tx = await this.client.order({id})
58
- processSimulationErrors(tx)
59
- return tx.result ?? undefined
60
- }
61
-
62
- /**
63
- * Fetch contract configuration.
64
- * @return {Promise<Config>}
65
- */
66
- async loadConfig() {
67
- const tx = await this.client.config()
68
- processSimulationErrors(tx)
69
- return tx.result
70
- }
71
-
72
- /**
73
- * Check whether the contract is frozen.
74
- * @return {Promise<boolean>} - `true` if contract is frozen (trading and order management operations blocked)
75
- */
76
- async isFrozen() {
77
- const tx = await this.client.frozen()
78
- processSimulationErrors(tx)
79
- return tx.result
80
- }
81
-
82
- /**
83
- * Fetch market for the given asset pair.
84
- * @param {string} selling - First market asset
85
- * @param {string} buying - Second market asset
86
- * @return {Promise<Market|undefined>} - Market record if the market exists
87
- */
88
- async getMarket(selling, buying) {
89
- const tx = await this.client.market({selling, buying})
90
- processSimulationErrors(tx)
91
- return tx.result ?? undefined
92
- }
93
-
94
- /**
95
- * Trade with DEX and create a buy limit order if the quote not executed in full.
96
- * @param {BuyTradeArguments} params
97
- * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
98
- * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
99
- * no reference price is available, any of the counter orders provided do not match selling/buying asset, or a live order with the same id exists
100
- */
101
- async buy(params) {
102
- return await execTrade(params, TradeDirection.Buy, this)
103
- }
104
-
105
- /**
106
- * Trade with DEX and create a sell limit order if the quote not executed in full.
107
- * @param {SellTradeArguments} params
108
- * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
109
- * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
110
- * no reference price is available, any of the counter orders provided do not match selling/buying asset, or a live order with the same id exists
111
- */
112
- async sell(params) {
113
- return await execTrade(params, TradeDirection.Sell, this)
114
- }
115
-
116
- /**
117
- * Update the amount, price, or expiration of several orders in place, or remove them.
118
- * Orders that no longer exist are skipped; expired orders revived with the new expiration.
119
- * A zero amount removes the order, expired ones included. An updated order's entry lifetime is
120
- * extended to cover its expiration +1 day. Approvals and removals work in a frozen contract.
121
- * A transaction can process up to 100 orders in one batch.
122
- * @param {UpdateArguments} params
123
- * @return {Promise<bigint[]>} - IDs of the orders to update
124
- * @throws {Error} - If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,
125
- * if the new amounts are not backed by the trader's balance and allowance, if the contract is frozen
126
- */
127
- async update(params) {
128
- const updates = params.updates.map(update => ({
129
- id: update.id,
130
- amount: update.amount,
131
- price: update.price,
132
- expires: BigInt(update.expires ?? 0)
133
- }))
134
- const approvals = (params.approvals ?? []).map(approval => {
135
- if (!approval.asset)
136
- throw new TypeError('An update approval must name its asset')
137
- return toApproval(approval, approval.asset)
138
- })
139
- const tx = await this.client.update({trader: params.trader, updates, approvals}, {fee: this.fee})
140
- processSimulationErrors(tx)
141
- this.updateFootprint(tx, updates.map(update => update.id))
142
- const result = await signAndSend(tx)
143
- return result
144
- }
145
-
146
- /**
147
- * Cancel existing orders, expired ones included. A transaction can process up to 100 orders in one batch.
148
- * @param {string} trader - Trader address
149
- * @param {bigint[]} ids - IDs of the orders to cancel (non-existent orders are ignored)
150
- * @return {Promise<void>}
151
- * @throws {Error} - If trader is not the owner of any existing order in `ids` or if the contract is frozen
152
- */
153
- async cancel(trader, ids) {
154
- await this.update({trader, updates: ids.map(id => ({id, amount: 0n, price: 0n}))})
155
- }
156
-
157
- /**
158
- * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader.
159
- * @param {string} trader - Trader address
160
- * @param {bigint} takerOrderId - ID of the order that serves as a taker
161
- * @param {bigint[]} orders - List of order IDs to match against
162
- * @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the taker received, surplus paid to the trader
163
- * @throws {Error} - If the taker order does not exist or has expired, if any of the orders provided do not match selling/buying asset,
164
- * if the taker order's owner or the trader cannot receive the bought asset, if the contract is frozen
165
- */
166
- async crossfill(trader, takerOrderId, orders) {
167
- const tx = await this.client.crossfill({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})
168
- processSimulationErrors(tx)
169
- //the traded assets come from the taker order, resolved while completing the footprint
170
- await this.updateTradeFootprint(tx, [], [takerOrderId], orders)
171
- const result = await signAndSend(tx)
172
- return [result[0], result[1], result[2]]
173
- }
174
-
175
- /**
176
- * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call.
177
- * @param {SwapArguments} params
178
- * @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens
179
- * @throws {Error} - If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,
180
- * if any of the orders provided do not match trade step selling/buying asset, if the trader cannot pay for the fills or receive tokens, if the contract is frozen
181
- */
182
- async swap(params) {
183
- const tx = await this.client.swap({
184
- direction: params.direction,
185
- trader: params.trader,
186
- selling: params.selling,
187
- selling_amount: params.sellingAmount,
188
- buying_amount: params.buyingAmount,
189
- path: params.path.map(step => ({asset: step.asset, orders: step.orders})),
190
- approve: toApproval(params.approve, params.selling)
191
- }, {fee: this.fee})
192
- processSimulationErrors(tx)
193
- const tokens = [params.selling, ...params.path.map(step => step.asset)]
194
- await this.updateTradeFootprint(tx, tokens, ...params.path.map(step => step.orders))
195
- const result = await signAndSend(tx)
196
- return [result[0], result[1]]
197
- }
198
-
199
- /**
200
- * Re-check both market assets against the price oracle and cache oracle prices.
201
- * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting
202
- * new limit orders; its outstanding orders stay cancellable and fillable. The record and the
203
- * cached prices are rewritten only when they change. When the simulation writes nothing (the market and the
204
- * cached prices are current, or the oracle has no newer price), the simulated result is
205
- * returned and no transaction is submitted.
206
- * @param {string} selling - First market asset
207
- * @param {string} buying - Second market asset
208
- * @return {Promise<Market|undefined>} - Updated market record, undefined if the market does not exist
209
- * @throws {Error} - If the contract is frozen
210
- */
211
- async requote(selling, buying) {
212
- const tx = await this.client.requote({selling, buying}, {fee: this.fee})
213
- processSimulationErrors(tx)
214
- if (tx.isReadCall)
215
- return tx.result ?? undefined //nothing changed on-chain
216
- const result = await signAndSend(tx)
217
- return result ?? undefined
218
- }
219
-
220
- /**
221
- * Extend oracle price feeds access for a market, creating the market if it does not exist yet.
222
- * @param {SubsidizeArguments} params
223
- * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) per oracle-listed asset
224
- * @throws {Error} - If `amount` is invalid, if the market does not exist and the amount is below the market listing fee,
225
- * if neither market asset is quoted by the oracle, if the contract is frozen
226
- */
227
- async subsidize(params) {
228
- const tx = await this.client.subsidize({
229
- sponsor: params.sponsor,
230
- selling: params.selling,
231
- buying: params.buying,
232
- amount: params.amount
233
- }, {fee: this.fee})
234
- processSimulationErrors(tx)
235
- const result = await signAndSend(tx)
236
- return result
237
- }
238
-
239
- /**
240
- * Extend the contract instance and code lifetime.
241
- * @return {Promise<void>}
242
- */
243
- async keepalive() {
244
- const tx = await this.client.keepalive({fee: this.fee})
245
- processSimulationErrors(tx)
246
- await signAndSend(tx)
247
- }
248
-
249
- /**
250
- * Declare all order ids of a simulated call in the read-write footprint (if enabled).
251
- * @param {contract.AssembledTransaction} tx - Simulated transaction
252
- * @param {...Array<bigint>} idLists - Order ids passed to the contract call
253
- * @private
254
- */
255
- updateFootprint(tx, ...idLists) {
256
- if (this.autoFootprint) {
257
- const orderIds = collectOrderIds(...idLists)
258
- ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)
259
- }
260
- }
261
-
262
- /**
263
- * Declare all order ids of a simulated trading call, and the entries the settlement may write for their makers,
264
- * in the read-write footprint (if enabled), so the transaction survives book changes before it is applied.
265
- * @param {contract.AssembledTransaction} tx - Simulated transaction
266
- * @param {string[]} tokens - Tokens the call trades
267
- * @param {...Array<bigint>} idLists - Order ids passed to the contract call
268
- * @return {Promise<void>}
269
- * @private
270
- */
271
- async updateTradeFootprint(tx, tokens, ...idLists) {
272
- if (this.autoFootprint) {
273
- const orderIds = collectOrderIds(...idLists)
274
- await completeFootprint(tx, this.client.options.contractId, orderIds, {server: this.server, tokens, assetCache: this.assetCache})
275
- }
276
- }
277
- }
278
-
279
- /**
280
- * Map the client-side approval to the contract `Approval` argument
281
- * @param {Approval} [approve]
282
- * @param {string} defaultAsset - Asset approved when `approve.asset` is not set
283
- * @return {{asset: string, amount: bigint, live_until: number}|undefined}
284
- * @internal
285
- */
286
- function toApproval(approve, defaultAsset) {
287
- if (!approve)
288
- return undefined
289
- return {asset: approve.asset ?? defaultAsset, amount: approve.amount, live_until: approve.liveUntil}
290
- }
291
-
292
- /**
293
- * Sign and submit a simulated transaction
294
- * @param {contract.AssembledTransaction} tx
295
- * @return {Promise<*>} - Parsed contract call result
296
- * @throws {Error} - If the transaction failed on-chain
297
- * @internal
298
- */
299
- async function signAndSend(tx) {
300
- const sent = await tx.signAndSend()
301
- processTransactionErrors(sent)
302
- return sent.result
303
- }
304
-
305
- async function execTrade(params, direction, context) {
306
- //the id of the order created for the remainder derives from the trader and this nonce; generated per call, never supplied by the caller
307
- const nonce = generateNonce()
308
- const payload = {
309
- direction: direction,
310
- kind: params.kind,
311
- trader: params.trader,
312
- amount: params.amount,
313
- selling: params.selling,
314
- buying: params.buying,
315
- price: params.price,
316
- orders: params.orders ?? [],
317
- nonce,
318
- expires: BigInt(params.expires ?? 0),
319
- approve: toApproval(params.approve, params.selling)
320
- }
321
- const tx = await context.client.trade(payload, {fee: context.fee})
322
- processSimulationErrors(tx)
323
- //the remainder of a Limit trade becomes an order under an id known in advance - declare it even if the simulation filled the quote
324
- const remainder = params.kind === OrderKind.Limit ? [orderId(params.trader, nonce)] : []
325
- await context.updateTradeFootprint(tx, [params.selling, params.buying], payload.orders, remainder)
326
- const result = await signAndSend(tx)
327
- return [result[0], result[1], result[2] ?? undefined]
328
- }
329
-
330
- /**
331
- * @typedef {{}} ClientInitializationParams
332
- * @property {string} publicKey - Public key of the account that will interact with the contract
333
- * @property {SignTransactionCallback} signTransaction - Callback for signing transactions generated by the client
334
- * @property {string} rpcUrl - URL of the RPC server
335
- * @property {string} contractId - DEX contract ID
336
- * @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)
337
- * @property {string} [fee] - Transaction fee (0.1 XLM by default)
338
- * @property {boolean} [autoFootprint] - Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default)
339
- */
340
-
341
- /**
342
- * @callback SignTransactionCallback - Callback for signing transactions generated by the client
343
- * @param {string} tx - Transaction XDR to sign
344
- * @param {{network: string, networkPassphrase: string, accountToSign: string}} context - Signing context
345
- * @return {Promise<{signedTxXdr: string, [signerAddress]: string}>} - Signed transaction response
346
- */
347
-
348
- /**
349
- * @typedef {{}} Approval - Token allowance granted to the contract as part of the call
350
- * @property {string} [asset] - Token the allowance is granted on
351
- * @property {bigint} amount - Absolute allowance amount (0 revokes the approval)
352
- * @property {number} liveUntil - Ledger sequence the allowance lives until
353
- */
354
-
355
- /**
356
- * @typedef {{}} TradeArguments
357
- * @property {OrderKind} kind - Trading order behavior
358
- * @property {string} trader - Trader address
359
- * @property {bigint} amount - Tokens amount
360
- * @property {string} selling - Selling token address
361
- * @property {string} buying - Buying token address
362
- * @property {bigint} price - Price a trader willing to accept
363
- * @property {Array<bigint>} [orders] - List of order IDs to match before creating the order on-chain
364
- * @property {bigint|number} [expires] - Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration
365
- * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)
366
- */
367
-
368
- /**
369
- * @typedef {{}} SellTradeArguments
370
- * @extends TradeArguments
371
- * @property {bigint} amount - Amount of `selling` tokens to sell
372
- * @property {bigint} price - Price a trader willing to accept, minimum `buying` tokens per 1 `selling`
373
- */
374
-
375
- /**
376
- * @typedef {{}} BuyTradeArguments
377
- * @extends TradeArguments
378
- * @property {bigint} amount - Amount of `buying` tokens to acquire
379
- * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`
380
- */
381
-
382
- /**
383
- * @typedef {{}} TradeStep - A trade step in a multi-market swap path
384
- * @property {string} asset - Asset to buy at this step
385
- * @property {Array<bigint>} orders - Maker order IDs to match
386
- */
387
-
388
- /**
389
- * @typedef {{}} SwapArguments - Swap path and settings
390
- * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`
391
- * @property {string} trader - Trader address
392
- * @property {string} selling - Token address sent by the trader
393
- * @property {bigint} sellingAmount - Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`)
394
- * @property {bigint} buyingAmount - Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`)
395
- * @property {Array<TradeStep>} path - Ordered list of the trade route steps
396
- * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)
397
- */
398
-
399
- /**
400
- * @typedef {{}} OrderUpdate - New amount, price and expiration for an existing order
401
- * @property {bigint} id - Order id
402
- * @property {bigint} amount - New amount to sell, 0 removes the order
403
- * @property {bigint} price - New order price (ignored for a removal)
404
- * @property {bigint|number} [expires] - New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration
405
- */
406
-
407
- /**
408
- * @typedef {{}} UpdateArguments
409
- * @property {string} trader - Orders owner
410
- * @property {Array<OrderUpdate>} updates - New amount, price and expiration per order
411
- * @property {Array<Approval>} [approvals] - Allowances granted before the backing check, each naming its `asset`; an asset
412
- * without an approval keeps its current allowance
413
- */
414
-
415
- /**
416
- * @typedef {{}} SubsidizeArguments
417
- * @property {string} sponsor - Address paying for the oracle feeds (and the listing fee of a new market)
418
- * @property {string} selling - First market asset
419
- * @property {string} buying - Second market asset (either order opens the same market)
420
- * @property {bigint} amount - Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market
421
- */
422
-
423
- /**
424
- * @typedef {{}} MethodOptions
425
- * @property {string} [fee] - Transaction fee (0.1 XLM by default)
426
- */
427
-
428
- /**
429
- * @typedef {{}} Order - Order properties, stored on-chain
430
- * @property {bigint} id - Unique order identifier, derived from the owner and the client nonce
431
- * @property {string} owner - Maker address
432
- * @property {string} selling - Selling token address
433
- * @property {string} buying - Buying token address
434
- * @property {bigint} amount - Amount left to sell
435
- * @property {bigint} price - Order price (`buying` per 1 `selling`, 18 decimals)
436
- * @property {bigint} expires - Expiration timestamp (0 = no expiration)
437
- */
438
-
439
- /**
440
- * @typedef {{}} Config - Contract configuration
441
- * @property {string} oracle - Oracle contract address
442
- * @property {bigint} market_listing_fee - Amount of oracle tokens burned by the market creator to provision the oracle price feeds (always the oracle daily fee x 90)
443
- * @property {string} safety_admin - Address of the account allowed to freeze the contract, change the minimum trade size and replace the oracle
444
- * @property {bigint} min_trade_size - Minimum trade value in USD, with 7 decimals precision (0 disables the limit)
445
- */
446
-
447
- /**
448
- * @typedef {{}} MarketSide - Market asset descriptor
449
- * @property {string} asset - Token contract address
450
- * @property {boolean} listed - Whether the asset is quoted by the oracle
451
- * @property {number} decimals - Token decimals (fetched only for listed assets)
452
- */
453
-
454
- /**
455
- * @typedef {{}} Market - Market record, stored on-chain
456
- * @property {MarketSide} a - First asset (canonical order)
457
- * @property {MarketSide} b - Second asset (canonical order)
458
- * @property {bigint} created - Creation timestamp
459
- */
460
-
461
- /**
462
- * @typedef {object} TradeContractEvent - Orderbook `trade` event, one per fill
463
- * @property {string} selling - Asset sold by the taker (topic)
464
- * @property {string} buying - Asset bought by the taker (topic)
465
- * @property {bigint} order - Maker order id
466
- * @property {string} taker - Trader account address
467
- * @property {string} maker - Seller account address
468
- * @property {bigint} sold - Sold tokens amount
469
- * @property {bigint} bought - Bought tokens amount
470
- * @property {bigint} left - Order amount left after the fill (0 = removed)
471
- */
472
-
473
- /**
474
- * @typedef {object} SwapContractEvent - Orderbook `swap` event, one per call
475
- * @property {string} selling - Asset sold by the trader (topic)
476
- * @property {string} buying - Asset received by the trader (topic)
477
- * @property {string} trader - Trader account address
478
- * @property {bigint} sold - Amount of `selling` tokens sold
479
- * @property {bigint} bought - Amount of `buying` tokens received
480
- */
481
-
482
- /**
483
- * @typedef {object} OrderCreatedContractEvent - Orderbook `new` event, an order created
484
- * @property {string} selling - Selling asset address (topic)
485
- * @property {string} buying - Buying asset address (topic)
486
- * @property {bigint} id - Unique order identifier
487
- * @property {string} owner - Maker address
488
- * @property {bigint} price - Order price
489
- * @property {bigint} amount - Current amount
490
- * @property {bigint} expires - Expiration timestamp (0 = no expiration)
491
- */
492
-
493
- /**
494
- * @typedef {object} OrderUpdatedContractEvent - Orderbook `mod` event, an order changed outside a fill
495
- * @property {bigint} id - Unique order identifier
496
- * @property {bigint} price - Order price
497
- * @property {bigint} amount - Current amount (0 = removed)
498
- * @property {bigint} expires - Expiration timestamp (0 = no expiration)
499
- */
500
-
501
- /**
502
- * @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle
503
- * (backing short of the fill, cannot receive the taker's asset, or the transfer failed); the order is left unchanged
504
- * @property {bigint} order - Order id
505
- */
506
-
507
- /**
508
- * @typedef {object} MarketRefreshContractEvent - Orderbook `refresh` event, a market checked against the oracle
509
- * (topics: `refresh`, `a`, `b`; no data)
510
- * @property {string} a - First market asset (canonical order, topic)
511
- * @property {string} b - Second market asset (canonical order, topic)
512
- */
513
-
514
- /**
515
- * @typedef {object} FreezeContractEvent - `freeze` event
516
- * @property {boolean} frozen - Whether trading is blocked after the call
517
- */
518
-
519
- /**
520
- * @typedef {object} ConfigChangedContractEvent - `config` update notification event
521
- * @property {Config} config - Contract configuration after the call
522
- */
1
+ import {Contract, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'
2
+ import ContractClient from './contract-client.js'
3
+ import {ContractErrors, TokenErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
4
+ import {AxisApiClient, AxisApiError} from './api-client.js'
5
+ import {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'
6
+ import {orderId, generateNonce} from './order-id.js'
7
+ import {OrderKind, TradeDirection} from './constants.js'
8
+
9
+ export {ContractErrors, TokenErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}
10
+ export {Axis, toWsUrl} from './axis.js'
11
+ export {AxisMarket} from './axis-market.js'
12
+ export {AxisAccount, parseApiOrder} from './axis-account.js'
13
+ export {AxisStreamClient} from './stream-client.js'
14
+ export {TokenBalance} from './token-balance.js'
15
+ export {Emitter} from './emitter.js'
16
+ export {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGERS} from './allowance.js'
17
+ export {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'
18
+ export {parseApiDate} from './api-dates.js'
19
+
20
+ const SECONDS_PER_DAY = 86_400
21
+ //ledger close time assumed when the contract configuration cannot be read, in seconds (the contract's default)
22
+ const DEFAULT_LEDGER_TIME = 5
23
+ //default lifetime `keepalive` extends the contract instance and code to, in days
24
+ const KEEPALIVE_DAYS = 30
25
+ //validity window of transactions built by the client, in seconds
26
+ const TX_TIMEOUT = 60
27
+
28
+ /**
29
+ * Smart contract client for trading with AXIS DEX
30
+ */
31
+ export class AxisContractClient {
32
+ /**
33
+ * @param {ClientInitializationParams} params
34
+ */
35
+ constructor(params) {
36
+ const options = {
37
+ publicKey: params.publicKey,
38
+ signTransaction: params.signTransaction,
39
+ rpcUrl: params.rpcUrl,
40
+ allowHttp: true,
41
+ networkPassphrase: params.networkPassphrase || Networks.PUBLIC,
42
+ contractId: params.contractId
43
+ }
44
+ this.client = new ContractClient(options)
45
+ this.fee = params.fee || '100000'
46
+ this.autoFootprint = params.autoFootprint !== false
47
+ this.server = new rpc.Server(params.rpcUrl, {allowHttp: true})
48
+ this.assetCache = new Map()
49
+ }
50
+
51
+ /**
52
+ * Account that signs and pays for the transactions
53
+ * @return {string}
54
+ */
55
+ get publicKey() {
56
+ return this.client.options.publicKey
57
+ }
58
+
59
+ /**
60
+ * Fetch existing order.
61
+ * @param {bigint} id - ID of the order to fetch
62
+ * @return {Promise<Order|undefined>} - Order fetched from the storage, undefined if not found or expired
63
+ */
64
+ async order(id) {
65
+ const tx = await this.client.order({id})
66
+ processSimulationErrors(tx)
67
+ return tx.result ?? undefined
68
+ }
69
+
70
+ /**
71
+ * Fetch contract configuration.
72
+ * @return {Promise<Config>}
73
+ */
74
+ async loadConfig() {
75
+ const tx = await this.client.config()
76
+ processSimulationErrors(tx)
77
+ return tx.result
78
+ }
79
+
80
+ /**
81
+ * Check whether the contract is frozen.
82
+ * @return {Promise<boolean>} - `true` if contract is frozen (trading and order management operations blocked)
83
+ */
84
+ async isFrozen() {
85
+ const tx = await this.client.frozen()
86
+ processSimulationErrors(tx)
87
+ return tx.result
88
+ }
89
+
90
+ /**
91
+ * Fetch market for the given asset pair.
92
+ * @param {string} selling - First market asset
93
+ * @param {string} buying - Second market asset
94
+ * @return {Promise<Market|undefined>} - Market record if the market exists
95
+ */
96
+ async getMarket(selling, buying) {
97
+ const tx = await this.client.market({selling, buying})
98
+ processSimulationErrors(tx)
99
+ return tx.result ?? undefined
100
+ }
101
+
102
+ /**
103
+ * Trade with DEX and create a buy limit order if the quote not executed in full.
104
+ * @param {BuyTradeArguments} params
105
+ * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
106
+ * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
107
+ * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
108
+ * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
109
+ */
110
+ async buy(params) {
111
+ return await execTrade(params, TradeDirection.Buy, this)
112
+ }
113
+
114
+ /**
115
+ * Trade with DEX and create a sell limit order if the quote not executed in full.
116
+ * @param {SellTradeArguments} params
117
+ * @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
118
+ * @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
119
+ * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
120
+ * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
121
+ */
122
+ async sell(params) {
123
+ return await execTrade(params, TradeDirection.Sell, this)
124
+ }
125
+
126
+ /**
127
+ * Simulate a buy trade without signing or submitting it, to show the network fee before the trade.
128
+ * @param {BuyTradeArguments} params
129
+ * @return {Promise<TradeEstimate>}
130
+ * @throws {Error} - If the simulation fails, for the same reasons as `buy`
131
+ */
132
+ async estimateBuy(params) {
133
+ return estimateTx(await prepareTrade(params, TradeDirection.Buy, this), this.fee)
134
+ }
135
+
136
+ /**
137
+ * Simulate a sell trade without signing or submitting it, to show the network fee before the trade.
138
+ * @param {SellTradeArguments} params
139
+ * @return {Promise<TradeEstimate>}
140
+ * @throws {Error} - If the simulation fails, for the same reasons as `sell`
141
+ */
142
+ async estimateSell(params) {
143
+ return estimateTx(await prepareTrade(params, TradeDirection.Sell, this), this.fee)
144
+ }
145
+
146
+ /**
147
+ * Update the amount, price, or expiration of several orders in place, or remove them.
148
+ * Orders that no longer exist are skipped; expired orders revived with the new expiration.
149
+ * A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover its expiration +1 day.
150
+ * Approvals and removals work in a frozen contract and on a market without quoted assets.
151
+ * A transaction can process up to 100 orders in one batch.
152
+ * @param {UpdateArguments} params
153
+ * @return {Promise<bigint[]>} - IDs of the orders to update
154
+ * @throws {Error} - If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,
155
+ * if the new amounts are not backed by the trader's balance and allowance, an update changes an order on the frozen or not-quoted market
156
+ */
157
+ async update(params) {
158
+ const updates = params.updates.map(update => ({
159
+ id: update.id,
160
+ amount: update.amount,
161
+ price: update.price,
162
+ expires: BigInt(update.expires ?? 0)
163
+ }))
164
+ const approvals = (params.approvals ?? []).map(approval => {
165
+ if (!approval.asset)
166
+ throw new TypeError('An update approval must name its asset')
167
+ return toApproval(approval, approval.asset)
168
+ })
169
+ const tx = await this.client.update({trader: params.trader, updates, approvals}, {fee: this.fee})
170
+ processSimulationErrors(tx)
171
+ this.updateFootprint(tx, updates.map(update => update.id))
172
+ const result = await signAndSend(tx)
173
+ return result
174
+ }
175
+
176
+ /**
177
+ * Cancel existing orders, expired ones included. A transaction can process up to 100 orders in one batch.
178
+ * @param {string} trader - Trader address
179
+ * @param {bigint[]} ids - IDs of the orders to cancel (non-existent orders are ignored)
180
+ * @return {Promise<void>}
181
+ * @throws {Error} - If trader is not the owner of any existing order in `ids` (works while the contract is frozen)
182
+ */
183
+ async cancel(trader, ids) {
184
+ await this.update({trader, updates: ids.map(id => ({id, amount: 0n, price: 0n}))})
185
+ }
186
+
187
+ /**
188
+ * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader.
189
+ * @param {string} trader - Trader address
190
+ * @param {bigint} takerOrderId - ID of the order that serves as a taker
191
+ * @param {bigint[]} orders - List of order IDs to match against
192
+ * @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the makers delivered, surplus paid to the trader.
193
+ * @throws {Error} - If the taker order does not exist or has expired, if the trader cannot receive the bought asset, if the
194
+ * contract cannot hold the bought asset, if the contract is frozen.
195
+ */
196
+ async crossfill(trader, takerOrderId, orders) {
197
+ const tx = await this.client.crossfill({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})
198
+ processSimulationErrors(tx)
199
+ //the traded assets come from the taker order, resolved while completing the footprint: what it buys passes
200
+ //through the contract, which pays the owner and the surplus to the trader
201
+ await this.updateTradeFootprint(tx, {takerOrder: takerOrderId, receiver: trader}, [takerOrderId], orders)
202
+ const result = await signAndSend(tx)
203
+ return [result[0], result[1], result[2]]
204
+ }
205
+
206
+ /**
207
+ * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call.
208
+ * @param {SwapArguments} params
209
+ * @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens
210
+ * @throws {Error} - If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,
211
+ * if the contract cannot hold an asset of the path, if the contract is frozen.
212
+ */
213
+ async swap(params) {
214
+ const tx = await this.client.swap({
215
+ direction: params.direction,
216
+ trader: params.trader,
217
+ selling: params.selling,
218
+ selling_amount: params.sellingAmount,
219
+ buying_amount: params.buyingAmount,
220
+ path: params.path.map(step => ({asset: step.asset, orders: step.orders})),
221
+ approve: toApproval(params.approve, params.selling)
222
+ }, {fee: this.fee})
223
+ processSimulationErrors(tx)
224
+ const hops = params.path.map(step => step.asset)
225
+ //every hop asset passes through the contract, the last one is forwarded to the trader
226
+ await this.updateTradeFootprint(tx, {
227
+ tokens: [params.selling, ...hops],
228
+ passThrough: hops,
229
+ receiver: params.trader,
230
+ bought: hops[hops.length - 1]
231
+ }, ...params.path.map(step => step.orders))
232
+ const result = await signAndSend(tx)
233
+ return [result[0], result[1]]
234
+ }
235
+
236
+ /**
237
+ * Re-check both market assets against the price oracle and cache oracle prices.
238
+ * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting
239
+ * new limit orders; its outstanding orders stay cancellable and fillable. The record and the
240
+ * cached prices are rewritten only when they change. When the simulation writes nothing (the market and the
241
+ * cached prices are current, or the oracle has no newer price), the simulated result is
242
+ * returned and no transaction is submitted.
243
+ * @param {string} selling - First market asset
244
+ * @param {string} buying - Second market asset
245
+ * @return {Promise<Market|undefined>} - Updated market record, undefined if the market does not exist
246
+ * @throws {Error} - If the contract is frozen
247
+ */
248
+ async requote(selling, buying) {
249
+ const tx = await this.client.requote({selling, buying}, {fee: this.fee})
250
+ processSimulationErrors(tx)
251
+ if (tx.isReadCall)
252
+ return tx.result ?? undefined //nothing changed on-chain
253
+ const result = await signAndSend(tx)
254
+ return result ?? undefined
255
+ }
256
+
257
+ /**
258
+ * Extend oracle price feeds access for a market, creating the market if it does not exist yet.
259
+ * @param {SubsidizeArguments} params
260
+ * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) per oracle-listed asset
261
+ * @throws {Error} - If `amount` is invalid, if `selling` equals `buying`, if the market does not exist and the amount is below
262
+ * the market listing fee, if neither market asset is quoted by the oracle, if the contract is frozen
263
+ */
264
+ async subsidize(params) {
265
+ const tx = await this.client.subsidize({
266
+ sponsor: params.sponsor,
267
+ selling: params.selling,
268
+ buying: params.buying,
269
+ amount: params.amount
270
+ }, {fee: this.fee})
271
+ processSimulationErrors(tx)
272
+ const result = await signAndSend(tx)
273
+ return result
274
+ }
275
+
276
+ /**
277
+ * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived
278
+ * ones first with a `RestoreFootprint` transaction.
279
+ * @param {number} [days] - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)
280
+ * @return {Promise<number>} - Ledger sequence both entries live at least until
281
+ * @throws {Error} - If `days` is invalid, if the instance is not found, if a simulation or a transaction fails
282
+ */
283
+ async keepalive(days = KEEPALIVE_DAYS) {
284
+ if (!Number.isInteger(days) || days <= 0)
285
+ throw new TypeError(`Invalid keepalive days: ${days}`)
286
+ const {keys, archived} = await contractLifetimeEntries(this.server, this.client.options.contractId)
287
+ if (archived.length)
288
+ await this.submitFootprintOperation(Operation.restoreFootprint({}), new SorobanDataBuilder().setReadWrite(archived))
289
+ //read after the restoration: the configuration is stored in the instance
290
+ const extendTo = Math.ceil(days * SECONDS_PER_DAY / await this.loadLedgerTime())
291
+ const simulation = await this.submitFootprintOperation(Operation.extendFootprintTtl({extendTo}), new SorobanDataBuilder().setReadOnly(keys))
292
+ return simulation.latestLedger + extendTo
293
+ }
294
+
295
+ /**
296
+ * Build, simulate, sign and submit a transaction with a single footprint operation (`ExtendFootprintTTL` or `RestoreFootprint`)
297
+ * @param {xdr.Operation} operation
298
+ * @param {SorobanDataBuilder} sorobanData - Footprint of the operation
299
+ * @return {Promise<rpc.Api.SimulateTransactionSuccessResponse>} - Simulation the submitted transaction was assembled from
300
+ * @private
301
+ */
302
+ async submitFootprintOperation(operation, sorobanData) {
303
+ const {networkPassphrase, signTransaction} = this.client.options
304
+ const tx = new TransactionBuilder(await this.server.getAccount(this.publicKey), {fee: this.fee, networkPassphrase})
305
+ .addOperation(operation)
306
+ .setSorobanData(sorobanData.build())
307
+ .setTimeout(TX_TIMEOUT)
308
+ .build()
309
+ const simulation = await this.server.simulateTransaction(tx)
310
+ if (rpc.Api.isSimulationError(simulation))
311
+ throw new Error(simulation.error)
312
+ if (rpc.Api.isSimulationRestore(simulation))
313
+ throw new Error('The contract instance or code was archived during the keepalive, retry it to restore them')
314
+ //assembled here, not through the contract client: its signing path declares the resource fee twice
315
+ const prepared = rpc.assembleTransaction(tx, simulation).build()
316
+ if (typeof signTransaction !== 'function')
317
+ throw new Error('No signTransaction callback to sign the keepalive transaction')
318
+ const {signedTxXdr, error} = await signTransaction(prepared.toXDR(), {networkPassphrase, address: this.publicKey})
319
+ if (error)
320
+ throw new Error(`Keepalive transaction was not signed: ${error.message ?? error}`)
321
+ await submitTransaction(this.server, TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase))
322
+ return simulation
323
+ }
324
+
325
+ /**
326
+ * Ledger close time the contract converts lifetimes with
327
+ * @return {Promise<number>} - Seconds per ledger
328
+ * @private
329
+ */
330
+ async loadLedgerTime() {
331
+ try {
332
+ return Number((await this.loadConfig())?.ledger_time) || DEFAULT_LEDGER_TIME
333
+ } catch (e) {
334
+ return DEFAULT_LEDGER_TIME //the extension itself reports an unreachable or archived contract
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Declare all order ids of a simulated call in the read-write footprint (if enabled).
340
+ * @param {contract.AssembledTransaction} tx - Simulated transaction
341
+ * @param {...Array<bigint>} idLists - Order ids passed to the contract call
342
+ * @private
343
+ */
344
+ updateFootprint(tx, ...idLists) {
345
+ if (this.autoFootprint) {
346
+ const orderIds = collectOrderIds(...idLists)
347
+ ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Declare all order ids of a simulated trading call, and the entries the settlement may write for their makers,
353
+ * in the read-write footprint (if enabled), so the transaction survives book changes before it is applied.
354
+ * @param {contract.AssembledTransaction} tx - Simulated transaction
355
+ * @param {{tokens?: string[], passThrough?: string[], receiver?: string, bought?: string, takerOrder?: bigint}} settlement - Tokens
356
+ * the call trades and how it settles (see `FootprintOptions`)
357
+ * @param {...Array<bigint>} idLists - Order ids passed to the contract call
358
+ * @return {Promise<void>}
359
+ * @private
360
+ */
361
+ async updateTradeFootprint(tx, settlement, ...idLists) {
362
+ if (this.autoFootprint) {
363
+ const orderIds = collectOrderIds(...idLists)
364
+ await completeFootprint(tx, this.client.options.contractId, orderIds, {...settlement, server: this.server, assetCache: this.assetCache})
365
+ }
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Ledger keys of the contract instance and its Wasm code, and those of them that are archived
371
+ * @param {rpc.Server} server
372
+ * @param {string} contractId
373
+ * @return {Promise<{keys: xdr.LedgerKey[], archived: xdr.LedgerKey[]}>}
374
+ * @internal
375
+ */
376
+ async function contractLifetimeEntries(server, contractId) {
377
+ const instanceKey = new Contract(contractId).getFootprint()
378
+ const instance = await server.getLedgerEntries(instanceKey)
379
+ const executable = instance.entries[0]?.val?.contractData?.val?.instance?.executable
380
+ if (!executable)
381
+ throw new Error(`Contract ${contractId} instance not found`)
382
+ if (!executable.wasmHash)
383
+ throw new Error(`Contract ${contractId} has no Wasm code`)
384
+ const codeKey = xdr.LedgerKey.contractCode(new xdr.LedgerKeyContractCode({hash: executable.wasmHash}))
385
+ const code = await server.getLedgerEntries(codeKey)
386
+ const archived = []
387
+ if (isArchived(instance.entries[0], instance.latestLedger))
388
+ archived.push(instanceKey)
389
+ //code the RPC does not return is evicted, the restoration brings it back
390
+ if (!code.entries[0] || isArchived(code.entries[0], code.latestLedger))
391
+ archived.push(codeKey)
392
+ return {keys: [instanceKey, codeKey], archived}
393
+ }
394
+
395
+ /**
396
+ * Whether a ledger entry is no longer live for the transactions following the latest ledger
397
+ * @param {rpc.Api.LedgerEntryResult} entry
398
+ * @param {number} latestLedger
399
+ * @return {boolean}
400
+ * @internal
401
+ */
402
+ function isArchived(entry, latestLedger) {
403
+ return entry.liveUntilLedgerSeq !== undefined && entry.liveUntilLedgerSeq <= latestLedger
404
+ }
405
+
406
+ /**
407
+ * Submit a signed transaction and wait for its result
408
+ * @param {rpc.Server} server
409
+ * @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
412
+ * @internal
413
+ */
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
423
+ }
424
+ if (res.status !== 'SUCCESS')
425
+ throw new Error(`Transaction ${sent.hash} was not included in time`)
426
+ }
427
+
428
+ /**
429
+ * Map the client-side approval to the contract `Approval` argument
430
+ * @param {Approval} [approve]
431
+ * @param {string} defaultAsset - Asset approved when `approve.asset` is not set
432
+ * @return {{asset: string, amount: bigint, live_until: number}|undefined}
433
+ * @internal
434
+ */
435
+ function toApproval(approve, defaultAsset) {
436
+ if (!approve)
437
+ return undefined
438
+ return {asset: approve.asset ?? defaultAsset, amount: approve.amount, live_until: approve.liveUntil}
439
+ }
440
+
441
+ /**
442
+ * Sign and submit a simulated transaction
443
+ * @param {contract.AssembledTransaction} tx
444
+ * @return {Promise<*>} - Parsed contract call result
445
+ * @throws {Error} - If the transaction failed on-chain
446
+ * @internal
447
+ */
448
+ async function signAndSend(tx) {
449
+ const sent = await tx.signAndSend()
450
+ processTransactionErrors(sent)
451
+ return sent.result
452
+ }
453
+
454
+ async function execTrade(params, direction, context) {
455
+ const result = await signAndSend(await prepareTrade(params, direction, context))
456
+ return [result[0], result[1], result[2] ?? undefined]
457
+ }
458
+
459
+ /**
460
+ * Simulate a trade and complete its footprint
461
+ * @param {BuyTradeArguments|SellTradeArguments} params
462
+ * @param {number} direction
463
+ * @param {AxisContractClient} context
464
+ * @return {Promise<contract.AssembledTransaction>}
465
+ * @internal
466
+ */
467
+ async function prepareTrade(params, direction, context) {
468
+ //the id of the order created for the remainder derives from the trader and this nonce; generated per call, never supplied by the caller
469
+ const nonce = generateNonce()
470
+ const payload = {
471
+ direction: direction,
472
+ kind: params.kind,
473
+ trader: params.trader,
474
+ amount: params.amount,
475
+ selling: params.selling,
476
+ buying: params.buying,
477
+ price: params.price,
478
+ orders: params.orders ?? [],
479
+ nonce,
480
+ expires: BigInt(params.expires ?? 0),
481
+ approve: toApproval(params.approve, params.selling)
482
+ }
483
+ const tx = await context.client.trade(payload, {fee: context.fee})
484
+ processSimulationErrors(tx)
485
+ //the remainder of a Limit trade becomes an order under an id known in advance - declare it even if the simulation filled the quote
486
+ const remainder = params.kind === OrderKind.Limit ? [orderId(params.trader, nonce)] : []
487
+ //the bought asset passes through the contract on its way to the trader
488
+ await context.updateTradeFootprint(tx, {
489
+ tokens: [params.selling, params.buying],
490
+ passThrough: [params.buying],
491
+ receiver: params.trader,
492
+ bought: params.buying
493
+ }, payload.orders, remainder)
494
+ return tx
495
+ }
496
+
497
+ /**
498
+ * Fee and expected result of a simulated transaction
499
+ * @param {contract.AssembledTransaction} tx - Simulated transaction with its footprint completed
500
+ * @param {string} inclusionFee - Inclusion fee bid of the client
501
+ * @return {TradeEstimate}
502
+ * @internal
503
+ */
504
+ function estimateTx(tx, inclusionFee) {
505
+ const fee = BigInt(tx.built.fee)
506
+ const [sold, bought, orderId] = tx.result
507
+ return {fee, inclusionFee: BigInt(inclusionFee), resourceFee: fee - BigInt(inclusionFee), sold, bought, orderId: orderId ?? undefined}
508
+ }
509
+
510
+ /**
511
+ * @typedef {{}} ClientInitializationParams
512
+ * @property {string} publicKey - Public key of the account that will interact with the contract
513
+ * @property {SignTransactionCallback} signTransaction - Callback for signing transactions generated by the client
514
+ * @property {string} rpcUrl - URL of the RPC server
515
+ * @property {string} contractId - DEX contract ID
516
+ * @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)
517
+ * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top
518
+ * @property {boolean} [autoFootprint] - Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default)
519
+ */
520
+
521
+ /**
522
+ * @callback SignTransactionCallback - Callback for signing transactions generated by the client (`@stellar/stellar-sdk` 17 contract client shape)
523
+ * @param {string} xdr - Transaction XDR to sign
524
+ * @param {{networkPassphrase?: string, address?: string, submit?: boolean, submitUrl?: string}} [opts] - Signing options passed by the SDK
525
+ * @return {Promise<{signedTxXdr: string, signerAddress?: string, error?: *}>} - Signed transaction response
526
+ */
527
+
528
+ /**
529
+ * @typedef {{}} Approval - Token allowance granted to the contract as part of the call
530
+ * @property {string} [asset] - Token the allowance is granted on
531
+ * @property {bigint} amount - Absolute allowance amount (0 revokes the approval)
532
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
533
+ */
534
+
535
+ /**
536
+ * @typedef {{}} TradeArguments
537
+ * @property {OrderKind} kind - Trading order behavior
538
+ * @property {string} trader - Trader address
539
+ * @property {bigint} amount - Tokens amount
540
+ * @property {string} selling - Selling token address
541
+ * @property {string} buying - Buying token address
542
+ * @property {bigint} price - Price a trader willing to accept
543
+ * @property {Array<bigint>} [orders] - List of order IDs to match before creating the order on-chain
544
+ * @property {bigint|number} [expires] - Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration
545
+ * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)
546
+ */
547
+
548
+ /**
549
+ * @typedef {{}} SellTradeArguments
550
+ * @extends TradeArguments
551
+ * @property {bigint} amount - Amount of `selling` tokens to sell
552
+ * @property {bigint} price - Price a trader willing to accept, minimum `buying` tokens per 1 `selling`
553
+ */
554
+
555
+ /**
556
+ * @typedef {{}} BuyTradeArguments
557
+ * @extends TradeArguments
558
+ * @property {bigint} amount - Amount of `buying` tokens to acquire
559
+ * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`
560
+ */
561
+
562
+ /**
563
+ * @typedef {{}} TradeEstimate - Simulated trade, nothing signed or submitted
564
+ * @property {bigint} fee - Maximum total network fee of the transaction, in stroops (inclusion fee bid plus resource fee)
565
+ * @property {bigint} inclusionFee - Inclusion fee bid, in stroops (the network charges the market rate up to it)
566
+ * @property {bigint} resourceFee - Resource fee, in stroops, including the rent of an order created for the remainder
567
+ * @property {bigint} sold - Expected amount of sold tokens
568
+ * @property {bigint} bought - Expected amount of bought tokens
569
+ * @property {bigint} [orderId] - ID of the order the remainder would create
570
+ */
571
+
572
+ /**
573
+ * @typedef {{}} TradeStep - A trade step in a multi-market swap path
574
+ * @property {string} asset - Asset to buy at this step
575
+ * @property {Array<bigint>} orders - Maker order IDs to match
576
+ */
577
+
578
+ /**
579
+ * @typedef {{}} SwapArguments - Swap path and settings
580
+ * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`
581
+ * @property {string} trader - Trader address
582
+ * @property {string} selling - Token address sent by the trader
583
+ * @property {bigint} sellingAmount - Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`)
584
+ * @property {bigint} buyingAmount - Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`)
585
+ * @property {Array<TradeStep>} path - Ordered list of the trade route steps
586
+ * @property {Approval} [approve] - Optional allowance granted to the contract before trading (on `selling` unless `asset` is set)
587
+ */
588
+
589
+ /**
590
+ * @typedef {{}} OrderUpdate - New amount, price and expiration for an existing order
591
+ * @property {bigint} id - Order id
592
+ * @property {bigint} amount - New amount to sell, 0 removes the order
593
+ * @property {bigint} price - New order price (ignored for a removal)
594
+ * @property {bigint|number} [expires] - New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration
595
+ */
596
+
597
+ /**
598
+ * @typedef {{}} UpdateArguments
599
+ * @property {string} trader - Orders owner
600
+ * @property {Array<OrderUpdate>} updates - New amount, price and expiration per order
601
+ * @property {Array<Approval>} [approvals] - Allowances granted before the backing check, each naming its `asset`; an asset
602
+ * without an approval keeps its current allowance
603
+ */
604
+
605
+ /**
606
+ * @typedef {{}} SubsidizeArguments
607
+ * @property {string} sponsor - Address paying for the oracle feeds (and the listing fee of a new market)
608
+ * @property {string} selling - First market asset
609
+ * @property {string} buying - Second market asset (either order opens the same market)
610
+ * @property {bigint} amount - Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market
611
+ */
612
+
613
+ /**
614
+ * @typedef {{}} MethodOptions
615
+ * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top
616
+ */
617
+
618
+ /**
619
+ * @typedef {{}} Order - Order properties, stored on-chain
620
+ * @property {bigint} id - Unique order identifier, derived from the owner and the client nonce
621
+ * @property {string} owner - Maker address
622
+ * @property {string} selling - Selling token address
623
+ * @property {string} buying - Buying token address
624
+ * @property {bigint} amount - Amount left to sell
625
+ * @property {bigint} price - Order price (`buying` per 1 `selling`, 18 decimals)
626
+ * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
627
+ */
628
+
629
+ /**
630
+ * @typedef {{}} Config - Contract configuration
631
+ * @property {string} safety_admin - Address of the account allowed to freeze the contract and change the configuration
632
+ * @property {string} oracle - Oracle contract address
633
+ * @property {number} listing_min_days - Days of price feeds a new market must buy (0 opens markets without a fee)
634
+ * @property {bigint} market_listing_fee - Amount of oracle fee tokens paid by the market creator to provision the oracle price feeds
635
+ * (the oracle daily fee x `listing_min_days`)
636
+ * @property {bigint} min_trade_size - Minimum trade value in USD, with 7 decimals precision (0 disables the limit)
637
+ * @property {number} ledger_time - Expected average ledger close time in seconds, used to convert entry lifetimes into ledgers
638
+ */
639
+
640
+ /**
641
+ * @typedef {{}} MarketSide - Market asset descriptor
642
+ * @property {string} asset - Token contract address
643
+ * @property {boolean} listed - Whether the asset is quoted by the oracle (with token decimals the valuation can handle)
644
+ * @property {number} decimals - Token decimals (fetched only for listed assets)
645
+ */
646
+
647
+ /**
648
+ * @typedef {{}} Market - Market record, stored on-chain
649
+ * @property {MarketSide} base - Base asset, the first of the pair in canonical order
650
+ * @property {MarketSide} quote - Quote asset, the second of the pair in canonical order
651
+ * @property {bigint} created - Creation UNIX timestamp in seconds
652
+ */
653
+
654
+ /**
655
+ * @typedef {object} TradeContractEvent - Orderbook `trade` event, one per fill
656
+ * @property {string} selling - Asset sold by the taker (topic)
657
+ * @property {string} buying - Asset bought by the taker (topic)
658
+ * @property {bigint} order - Maker order id
659
+ * @property {string} taker - Trader account address
660
+ * @property {string} maker - Seller account address
661
+ * @property {bigint} sold - Sold tokens amount
662
+ * @property {bigint} bought - Bought tokens amount
663
+ * @property {bigint} left - Order amount left after the fill (0 = removed)
664
+ */
665
+
666
+ /**
667
+ * @typedef {object} SwapContractEvent - Orderbook `swap` event, one per call
668
+ * @property {string} selling - Asset sold by the trader (topic)
669
+ * @property {string} buying - Asset received by the trader (topic)
670
+ * @property {string} trader - Trader account address
671
+ * @property {bigint} sold - Amount of `selling` tokens sold
672
+ * @property {bigint} bought - Amount of `buying` tokens received
673
+ */
674
+
675
+ /**
676
+ * @typedef {object} OrderCreatedContractEvent - Orderbook `new` event, an order created
677
+ * @property {string} selling - Selling asset address (topic)
678
+ * @property {string} buying - Buying asset address (topic)
679
+ * @property {bigint} id - Unique order identifier
680
+ * @property {string} owner - Maker address
681
+ * @property {bigint} price - Order price
682
+ * @property {bigint} amount - Current amount
683
+ * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
684
+ */
685
+
686
+ /**
687
+ * @typedef {object} OrderUpdatedContractEvent - Orderbook `mod` event, an order changed outside a fill
688
+ * @property {bigint} id - Unique order identifier
689
+ * @property {bigint} price - Order price
690
+ * @property {bigint} amount - Current amount (0 = removed)
691
+ * @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
692
+ */
693
+
694
+ /**
695
+ * @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle: backing
696
+ * short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected.
697
+ * The order is left unchanged. For `crossfill` it also flags a taker order its owner cannot back or be paid for
698
+ * @property {bigint} order - Order id
699
+ */
700
+
701
+ /**
702
+ * @typedef {object} MarketRefreshContractEvent - Orderbook `refresh` event, a market checked against the oracle
703
+ * (topics: `refresh`, `base`, `quote`, no data)
704
+ * @property {string} base - Base market asset (canonical order, topic)
705
+ * @property {string} quote - Quote market asset (canonical order, topic)
706
+ */
707
+
708
+ /**
709
+ * @typedef {object} FreezeContractEvent - `freeze` event
710
+ * @property {boolean} frozen - Whether trading is blocked after the call
711
+ */
712
+
713
+ /**
714
+ * @typedef {object} ConfigChangedContractEvent - `config` update notification event (constructor, `delegate`, `set_oracle`,
715
+ * `set_floor`, `set_listing_min_days`, `set_ledger_time`)
716
+ * @property {Config} config - Contract configuration after the call
717
+ */