@axis-markets/client 0.5.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,26 +1,29 @@
1
- import {Networks, contract} from '@stellar/stellar-sdk'
1
+ import {Contract, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'
2
2
  import ContractClient from './contract-client.js'
3
- import {ContractErrors, processSimulationErrors} from './errors.js'
3
+ import {ContractErrors, TokenErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
4
4
  import {AxisApiClient, AxisApiError} from './api-client.js'
5
- import {collectOrderIds, ensureOrdersFootprint} from './footprint.js'
6
-
7
- export {ContractErrors, AxisApiClient, AxisApiError}
8
-
9
- /** Trading order type - instructions to contract how to execute the trade */
10
- export const OrderKind = {
11
- /** Execute trade, create a limit order if not executed in full */
12
- Limit: 1,
13
- /** Execute trade without creating a limit order */
14
- Fill: 2,
15
- /** Execute trade, cancel if was not executed in full */
16
- FillOrKill: 3
17
- }
5
+ import {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'
6
+ import {orderId, generateNonce} from './order-id.js'
7
+ import {OrderKind, TradeDirection} from './constants.js'
18
8
 
19
- /** Trade direction instructions */
20
- export const TradeDirection = {
21
- Sell: 1,
22
- Buy: 2
23
- }
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
24
27
 
25
28
  /**
26
29
  * Smart contract client for trading with AXIS DEX
@@ -41,96 +44,172 @@ export class AxisContractClient {
41
44
  this.client = new ContractClient(options)
42
45
  this.fee = params.fee || '100000'
43
46
  this.autoFootprint = params.autoFootprint !== false
47
+ this.server = new rpc.Server(params.rpcUrl, {allowHttp: true})
48
+ this.assetCache = new Map()
44
49
  }
45
50
 
46
51
  /**
47
- * Declare all order ids of a simulated call in the read-write footprint (if enabled)
48
- * @param {contract.AssembledTransaction} tx - Simulated transaction
49
- * @param {...Array<bigint>} idLists - Order ids passed to the contract call
50
- * @private
52
+ * Account that signs and pays for the transactions
53
+ * @return {string}
51
54
  */
52
- updateFootprint(tx, ...idLists) {
53
- if (this.autoFootprint) {
54
- const orderIds = collectOrderIds(...idLists)
55
- ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)
56
- }
55
+ get publicKey() {
56
+ return this.client.options.publicKey
57
57
  }
58
58
 
59
59
  /**
60
- * Retrieve last order id
61
- * @return {Promise<bigint>} - Last created order id
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
62
63
  */
63
- async last() {
64
- const tx = await this.client.last()
64
+ async order(id) {
65
+ const tx = await this.client.order({id})
65
66
  processSimulationErrors(tx)
66
- return tx.result
67
+ return tx.result ?? undefined
67
68
  }
68
69
 
69
70
  /**
70
- * @param {bigint} id - ID of the order to fetch
71
- * @return {Promise<Order>} - Order fetched from the storage
71
+ * Fetch contract configuration.
72
+ * @return {Promise<Config>}
72
73
  */
73
- async order(id) {
74
- const tx = await this.client.order({id})
74
+ async loadConfig() {
75
+ const tx = await this.client.config()
75
76
  processSimulationErrors(tx)
76
77
  return tx.result
77
78
  }
78
79
 
79
80
  /**
80
- * Cancel existing order
81
- * @param {bigint[]} ids - ID of the order to cancel
82
- * @param {string} trader - Trader address
83
- * @return {Promise<void>}
84
- * @throws {Error} - If trader is not the owner of the order
81
+ * Check whether the contract is frozen.
82
+ * @return {Promise<boolean>} - `true` if contract is frozen (trading and order management operations blocked)
85
83
  */
86
- async cancel(ids, trader) {
87
- const tx = await this.client.cancel({ids, trader}, {fee: this.fee})
84
+ async isFrozen() {
85
+ const tx = await this.client.frozen()
88
86
  processSimulationErrors(tx)
89
- await tx.signAndSend()
87
+ return tx.result
90
88
  }
91
89
 
92
90
  /**
93
- * Fill existing orders using another matching order from the orderbook
94
- * @param {string} trader - Trader address
95
- * @param {bigint} takerOrderId - ID of the order that serves as a taker
96
- * @param {bigint[]} orders - List of order IDs to match before creating the order on chain
97
- * @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens
98
- * @throws {Error} - If the taker order was not found
99
- * @throws {Error} - If any of the orders provided do not match selling/buying asset
100
- * @throws {Error} - If the trade causes an overflow
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
101
95
  */
102
- async fill_order(trader, takerOrderId, orders) {
103
- const tx = await this.client.fill_order({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})
96
+ async getMarket(selling, buying) {
97
+ const tx = await this.client.market({selling, buying})
104
98
  processSimulationErrors(tx)
105
- this.updateFootprint(tx, [takerOrderId], orders)
106
- const res = await tx.signAndSend()
107
- return [res.result.sold, res.result.bought]
99
+ return tx.result ?? undefined
108
100
  }
109
101
 
110
102
  /**
111
- * Trade with DEX and create buy limit order if quote not executed in full
103
+ * Trade with DEX and create a buy limit order if the quote not executed in full.
112
104
  * @param {BuyTradeArguments} params
113
- * @return {Promise<[bigint, bigint, bigint]>} - Amount of sold and bought tokens, ID of the newly created order if any
114
- * @throws {Error} - If the trader has insufficient balance
115
- * @throws {Error} - If any of the orders provided do not match selling/buying asset
116
- * @throws {Error} - If the trade causes an overflow
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`).
117
109
  */
118
110
  async buy(params) {
119
111
  return await execTrade(params, TradeDirection.Buy, this)
120
112
  }
121
113
 
122
114
  /**
123
- * Trade with DEX and create sell limit order if quote not executed in full
115
+ * Trade with DEX and create a sell limit order if the quote not executed in full.
124
116
  * @param {SellTradeArguments} params
125
- * @return {Promise<[bigint, bigint, bigint]>} - Amount of sold and bought tokens, ID of the newly created order if any
126
- * @throws {Error} - If the trader has insufficient balance
127
- * @throws {Error} - If any of the orders provided do not match selling/buying asset
128
- * @throws {Error} - If the trade causes an overflow
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`).
129
121
  */
130
122
  async sell(params) {
131
123
  return await execTrade(params, TradeDirection.Sell, this)
132
124
  }
133
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
+ */
134
213
  async swap(params) {
135
214
  const tx = await this.client.swap({
136
215
  direction: params.direction,
@@ -138,16 +217,256 @@ export class AxisContractClient {
138
217
  selling: params.selling,
139
218
  selling_amount: params.sellingAmount,
140
219
  buying_amount: params.buyingAmount,
141
- path: params.path.map(step => ({asset: step.asset, orders: step.orders}))
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
142
270
  }, {fee: this.fee})
143
271
  processSimulationErrors(tx)
144
- this.updateFootprint(tx, ...params.path.map(step => step.orders))
145
- const res = await tx.signAndSend()
146
- return [res.result.sold, res.result.bought]
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
+ }
147
366
  }
148
367
  }
149
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
+
150
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()
151
470
  const payload = {
152
471
  direction: direction,
153
472
  kind: params.kind,
@@ -156,13 +475,36 @@ async function execTrade(params, direction, context) {
156
475
  selling: params.selling,
157
476
  buying: params.buying,
158
477
  price: params.price,
159
- orders: params.orders
478
+ orders: params.orders ?? [],
479
+ nonce,
480
+ expires: BigInt(params.expires ?? 0),
481
+ approve: toApproval(params.approve, params.selling)
160
482
  }
161
483
  const tx = await context.client.trade(payload, {fee: context.fee})
162
484
  processSimulationErrors(tx)
163
- context.updateFootprint(tx, params.orders)
164
- const {result} = await tx.signAndSend()
165
- return [result[0], result[1], result[2]]
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}
166
508
  }
167
509
 
168
510
  /**
@@ -172,15 +514,22 @@ async function execTrade(params, direction, context) {
172
514
  * @property {string} rpcUrl - URL of the RPC server
173
515
  * @property {string} contractId - DEX contract ID
174
516
  * @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)
175
- * @property {string} [fee] - Transaction fee (0.1 XLM by default)
176
- * @property {boolean} [autoFootprint] - Declare every supplied order id in the read-write footprint of trading transactions (enabled 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)
177
519
  */
178
520
 
179
521
  /**
180
- * @callback SignTransactionCallback - Callback for signing transactions generated by the client
181
- * @param {string} tx - Transaction XDR to sign
182
- * @param {{network: string, networkPassphrase: string, accountToSign: string}} context - Signing context
183
- * @return {Promise<{signedTxXdr: string, [signerAddress]: string}>} - Signed transaction response
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
184
533
  */
185
534
 
186
535
  /**
@@ -191,7 +540,9 @@ async function execTrade(params, direction, context) {
191
540
  * @property {string} selling - Selling token address
192
541
  * @property {string} buying - Buying token address
193
542
  * @property {bigint} price - Price a trader willing to accept
194
- * @property {Array<bigint>} orders - List of order IDs to match before creating the order on-chain
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)
195
546
  */
196
547
 
197
548
  /**
@@ -208,6 +559,16 @@ async function execTrade(params, direction, context) {
208
559
  * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`
209
560
  */
210
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
+
211
572
  /**
212
573
  * @typedef {{}} TradeStep - A trade step in a multi-market swap path
213
574
  * @property {string} asset - Asset to buy at this step
@@ -215,51 +576,142 @@ async function execTrade(params, direction, context) {
215
576
  */
216
577
 
217
578
  /**
218
- * @typedef {{}} SwapArguments
579
+ * @typedef {{}} SwapArguments - Swap path and settings
219
580
  * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`
220
581
  * @property {string} trader - Trader address
221
582
  * @property {string} selling - Token address sent by the trader
222
- * @property {bigint} selling_amount - Maximum amount of selling tokens to send
223
- * @property {bigint} buying_amount - Minimum amount of buying tokens to receive
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`)
224
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
225
611
  */
226
612
 
227
613
  /**
228
614
  * @typedef {{}} MethodOptions
229
- * @property {string} [fee] - Transaction fee (0.1 XLM by default)
615
+ * @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top
230
616
  */
231
617
 
232
618
  /**
233
619
  * @typedef {{}} Order - Order properties, stored on-chain
234
- * @property {bigint} id - Order ID
235
- * @property {OrderKind} kind - Trading behavior
236
- * @property {string} owner - Owner of the order
620
+ * @property {bigint} id - Unique order identifier, derived from the owner and the client nonce
621
+ * @property {string} owner - Maker address
237
622
  * @property {string} selling - Selling token address
238
623
  * @property {string} buying - Buying token address
239
- * @property {bigint} amount - Amount of tokens to sell
240
- * @property {bigint} price - Price of the order
241
- * @property {bigint} quote - Total amount of tokens to buy
242
- * @property {bigint} expires - Expiration time of the order
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
243
652
  */
244
653
 
245
654
  /**
246
- * @typedef {object} TradeContractEvent - Orderbook trade event
247
- * @property {bigint} bought - Bought tokens amount
248
- * @property {string} buying - Bought asset address
249
- * @property {bigint} id - Unique trade id
250
- * @property {string} maker - Seller account address
251
- * @property {bigint} order - Order id
252
- * @property {string} selling - Sold asset address
253
- * @property {bigint} sold - Sold tokens amount
254
- * @property {string} taker - Trader account address
255
- */
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
+ */
256
665
 
257
666
  /**
258
- * @typedef {object} SwapContractEvent - Orderbook swap event
259
- * @property {bigint} id - Unique swap id (last trade id assigned while settling the swap legs)
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)
260
670
  * @property {string} trader - Trader account address
261
- * @property {string} selling - Sold asset address
262
- * @property {string} buying - Bought asset address
263
671
  * @property {bigint} sold - Amount of `selling` tokens sold
264
672
  * @property {bigint} bought - Amount of `buying` tokens received
265
- */
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
+ */