@axis-markets/client 0.5.0 → 0.7.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,265 +1,522 @@
1
- import {Networks, contract} from '@stellar/stellar-sdk'
2
- import ContractClient from './contract-client.js'
3
- import {ContractErrors, processSimulationErrors} from './errors.js'
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
- }
18
-
19
- /** Trade direction instructions */
20
- export const TradeDirection = {
21
- Sell: 1,
22
- Buy: 2
23
- }
24
-
25
- /**
26
- * Smart contract client for trading with AXIS DEX
27
- */
28
- export class AxisContractClient {
29
- /**
30
- * @param {ClientInitializationParams} params
31
- */
32
- constructor(params) {
33
- const options = {
34
- publicKey: params.publicKey,
35
- signTransaction: params.signTransaction,
36
- rpcUrl: params.rpcUrl,
37
- allowHttp: true,
38
- networkPassphrase: params.networkPassphrase || Networks.PUBLIC,
39
- contractId: params.contractId
40
- }
41
- this.client = new ContractClient(options)
42
- this.fee = params.fee || '100000'
43
- this.autoFootprint = params.autoFootprint !== false
44
- }
45
-
46
- /**
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
51
- */
52
- updateFootprint(tx, ...idLists) {
53
- if (this.autoFootprint) {
54
- const orderIds = collectOrderIds(...idLists)
55
- ensureOrdersFootprint(tx, this.client.options.contractId, orderIds)
56
- }
57
- }
58
-
59
- /**
60
- * Retrieve last order id
61
- * @return {Promise<bigint>} - Last created order id
62
- */
63
- async last() {
64
- const tx = await this.client.last()
65
- processSimulationErrors(tx)
66
- return tx.result
67
- }
68
-
69
- /**
70
- * @param {bigint} id - ID of the order to fetch
71
- * @return {Promise<Order>} - Order fetched from the storage
72
- */
73
- async order(id) {
74
- const tx = await this.client.order({id})
75
- processSimulationErrors(tx)
76
- return tx.result
77
- }
78
-
79
- /**
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
85
- */
86
- async cancel(ids, trader) {
87
- const tx = await this.client.cancel({ids, trader}, {fee: this.fee})
88
- processSimulationErrors(tx)
89
- await tx.signAndSend()
90
- }
91
-
92
- /**
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
101
- */
102
- async fill_order(trader, takerOrderId, orders) {
103
- const tx = await this.client.fill_order({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})
104
- processSimulationErrors(tx)
105
- this.updateFootprint(tx, [takerOrderId], orders)
106
- const res = await tx.signAndSend()
107
- return [res.result.sold, res.result.bought]
108
- }
109
-
110
- /**
111
- * Trade with DEX and create buy limit order if quote not executed in full
112
- * @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
117
- */
118
- async buy(params) {
119
- return await execTrade(params, TradeDirection.Buy, this)
120
- }
121
-
122
- /**
123
- * Trade with DEX and create sell limit order if quote not executed in full
124
- * @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
129
- */
130
- async sell(params) {
131
- return await execTrade(params, TradeDirection.Sell, this)
132
- }
133
-
134
- async swap(params) {
135
- const tx = await this.client.swap({
136
- direction: params.direction,
137
- trader: params.trader,
138
- selling: params.selling,
139
- selling_amount: params.sellingAmount,
140
- buying_amount: params.buyingAmount,
141
- path: params.path.map(step => ({asset: step.asset, orders: step.orders}))
142
- }, {fee: this.fee})
143
- 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]
147
- }
148
- }
149
-
150
- async function execTrade(params, direction, context) {
151
- const payload = {
152
- direction: direction,
153
- kind: params.kind,
154
- trader: params.trader,
155
- amount: params.amount,
156
- selling: params.selling,
157
- buying: params.buying,
158
- price: params.price,
159
- orders: params.orders
160
- }
161
- const tx = await context.client.trade(payload, {fee: context.fee})
162
- processSimulationErrors(tx)
163
- context.updateFootprint(tx, params.orders)
164
- const {result} = await tx.signAndSend()
165
- return [result[0], result[1], result[2]]
166
- }
167
-
168
- /**
169
- * @typedef {{}} ClientInitializationParams
170
- * @property {string} publicKey - Public key of the account that will interact with the contract
171
- * @property {SignTransactionCallback} signTransaction - Callback for signing transactions generated by the client
172
- * @property {string} rpcUrl - URL of the RPC server
173
- * @property {string} contractId - DEX contract ID
174
- * @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)
177
- */
178
-
179
- /**
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
184
- */
185
-
186
- /**
187
- * @typedef {{}} TradeArguments
188
- * @property {OrderKind} kind - Trading order behavior
189
- * @property {string} trader - Trader address
190
- * @property {bigint} amount - Tokens amount
191
- * @property {string} selling - Selling token address
192
- * @property {string} buying - Buying token address
193
- * @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
195
- */
196
-
197
- /**
198
- * @typedef {{}} SellTradeArguments
199
- * @extends TradeArguments
200
- * @property {bigint} amount - Amount of `selling` tokens to sell
201
- * @property {bigint} price - Price a trader willing to accept, minimum `buying` tokens per 1 `selling`
202
- */
203
-
204
- /**
205
- * @typedef {{}} BuyTradeArguments
206
- * @extends TradeArguments
207
- * @property {bigint} amount - Amount of `buying` tokens to acquire
208
- * @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`
209
- */
210
-
211
- /**
212
- * @typedef {{}} TradeStep - A trade step in a multi-market swap path
213
- * @property {string} asset - Asset to buy at this step
214
- * @property {Array<bigint>} orders - Maker order IDs to match
215
- */
216
-
217
- /**
218
- * @typedef {{}} SwapArguments
219
- * @property {TradeDirection} direction - Trade direction: `Sell` or `Buy`
220
- * @property {string} trader - Trader address
221
- * @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
224
- * @property {Array<TradeStep>} path - Ordered list of the trade route steps
225
- */
226
-
227
- /**
228
- * @typedef {{}} MethodOptions
229
- * @property {string} [fee] - Transaction fee (0.1 XLM by default)
230
- */
231
-
232
- /**
233
- * @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
237
- * @property {string} selling - Selling token address
238
- * @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
243
- */
244
-
245
- /**
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
- */
256
-
257
- /**
258
- * @typedef {object} SwapContractEvent - Orderbook swap event
259
- * @property {bigint} id - Unique swap id (last trade id assigned while settling the swap legs)
260
- * @property {string} trader - Trader account address
261
- * @property {string} selling - Sold asset address
262
- * @property {string} buying - Bought asset address
263
- * @property {bigint} sold - Amount of `selling` tokens sold
264
- * @property {bigint} bought - Amount of `buying` tokens received
265
- */
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
+ */