@axis-markets/client 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,660 +1,684 @@
1
- # @axis-markets/client
2
-
3
- JavaScript SDK for [AXIS](https://axis.markets) Stellar DEX.
4
-
5
- - **`Axis`**, **`AxisMarket`**, **`AxisAccount`** - high-level API stateful: the DEX state (contract, markets) and a
6
- trader's open orders and allowances kept in memory from the AXIS API WebSocket push channel, with trading calls that
7
- look up the crossing orders and manage allowances automatically.
8
- - **`AxisContractClient`** — wraps the on-chain AXIS smart contract for order management and trading (sign & send
9
- transactions, read orders, markets and configuration).
10
- - **`AxisApiClient`** - a dependency-free HTTP client for the AXIS REST API (quotes, orderbook depth, candles, ticker,
11
- market/order/trade data).
12
- - **`AxisStreamClient`** - WebSocket client of the AXIS API push channel.
13
-
14
- ## Installation
15
-
16
- ```
17
- npm i @axis-markets/client
18
- ```
19
-
20
- Requires Node.js 22+ (or any modern browser). `@stellar/stellar-sdk` 17+ is a peer dependency (v17 changed the XDR
21
- representation and is not source-compatible with v16).
22
-
23
- ## Axis — high-level API
24
-
25
- `Axis` wrapper follows the contract state (frozen switch, configuration) and every market through the AXIS API push API,
26
- falling back to REST polling while the push connection is down. `axis.account()`
27
- returns an `AxisAccount` that keeps in memory all open orders of a trader across every market, and the trader's
28
- spendable balance and allowance in every market token, and trades with automatic allowance management. The AXIS API's
29
- data source streams updates for that state to maintain consistent up-to-date state in memory.
30
-
31
- The samples use the Testnet AXIS API (`https://demo-api.axis.markets`, push API at `wss://demo-api.axis.markets/ws`)
32
- and the Testnet tokens below.
33
-
34
- ```js
35
- import {Axis, TradeDirection} from '@axis-markets/client'
36
-
37
- //testnet token contracts
38
- const XLM = 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC'
39
- const USDC = 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA'
40
- const EURC = 'CCUUDM434BMZMYWYDITHFXHDMIVTGGD6T2I5UKNX5BSLXLW7HVR4MCGZ'
41
-
42
- const axis = new Axis({
43
- apiUrl: 'https://demo-api.axis.markets',
44
- rpcUrl: 'https://soroban-testnet.stellar.org',
45
- networkPassphrase: 'Test SDF Network ; September 2015'
46
- })
47
- await axis.connect() // the contract address comes from the AXIS API
48
- axis.on('frozen', frozen => console.log('trading', frozen ? 'suspended' : 'resumed'))
49
-
50
- const market = axis.getMarket(XLM, USDC) // either order: market.base / market.quote are in the contract order
51
-
52
- const account = axis.account(publicKey, {signTransaction})
53
- await account.ready
54
- account.on('fill', ({order, sold, bought}) => console.log(`order ${order.id}: sold ${sold}, got ${bought}`))
55
- account.on('filled', ({order}) => console.log(`order ${order.id} filled`))
56
- account.on('expire', order => console.log(`order ${order.id} expired`))
57
- account.on('backing', ({asset}) => console.log(asset, 'balance', account.getBalance(asset)))
58
-
59
- // network fee of the trade before signing anything (a simulation with the same crossing and approval)
60
- const {fee} = await account.estimateSell({selling: XLM, buying: USDC, amount: 1_000_000_000n, price: 25n * 10n ** 16n})
61
- // limit sell of 100 XLM at 0.25 USDC; crossing orders and the approval are handled by the account
62
- const {sold, bought, orderId} = await account.sell({
63
- selling: XLM,
64
- buying: USDC,
65
- amount: 1_000_000_000n,
66
- price: 25n * 10n ** 16n
67
- })
68
- // market buy of 10 XLM (no price: crosses the book at the worst quoted maker price)
69
- await account.buy({selling: USDC, buying: XLM, amount: 100_000_000n})
70
- await account.update([{id: orderId, amount: 500_000_000n}])
71
- await account.cancelAll({market})
72
- await account.swap({selling: USDC, buying: EURC, amount: 10_000_000n, direction: TradeDirection.Sell, slippage: 0.005})
73
- ```
74
-
75
- **Allowances.** The contract holds no funds: an order is fillable up to `min(balance, allowance)` in the sold token, and
76
- one allowance record backs every order selling it. Before each `sell`, `buy`, `swap` and a growing `update`, the account
77
- checks the allowance and attaches to cover all active orders. A new allowance lives `account.approvalTtl` ledgers
78
- (`APPROVAL_TTL_LEDGERS`, ~180 days, unless set with `axis.account(address, {approvalTtl})`). A fill lowers the allowance and the order it fills in the
79
- same pushed ledger, so the memory state stays consistent. The allowance is read over RPC only when the push connection
80
- is down, the token is not tracked, or for 30 s after this client spent the token as a taker (the push reporting the
81
- spend may lag behind). An order this client created counts as committed right away (`pending: true`) until the indexer
82
- reports it.
83
-
84
- **Balances.** While an account is subscribed, the AXIS API tracks it in every market token.
85
- `account.balances` / `getBalance(asset)` give the spendable amount, and each change emits
86
- `backing` event.
87
-
88
- **Backing.** Each `AccountOrder` carries `backed` (its share of the budget, split by the indexer among the orders
89
- selling the token oldest first), `backedPct` and `backingPending`.
90
- `account.getAllowance(asset)` reports `balance`, `allowance`, `liveUntil`, `available` and `committed`.
91
-
92
- | `Axis` | Description |
93
- |---|---|
94
- | `connect()` | Load the contract state and follow its changes. |
95
- | `contractId`, `getContractId()` | AXIS contract address. |
96
- | `ledger`, `getLedger()` | Last ledger pushed by the AXIS API; current ledger (pushed, or RPC when stale). |
97
- | `frozen`, `config`, `markets`, `loaded` | Contract state; `markets` is a `Map` of `AxisMarket` by canonical key. |
98
- | `getMarket(x, y)` | Market of the asset pair in either order, `undefined` if not open. |
99
- | `getOrder(id)` | Live order from a tracked account's memory or the AXIS API, `undefined` if gone. |
100
- | `account(address, {signTransaction, approvalTtl?})` | `AxisAccount` of the trader (one per address), `approvalTtl` sets the lifetime of the allowances it grants in ledgers. |
101
- | `subscribeTicker(cb)` | 24h ticker of every market (canonical orientation); also fills `market.ticker`. |
102
- | `keepalive({days?, signer?})` | Extend the contract instance and code lifetime, see `AxisContractClient.keepalive`. |
103
- | `close()` | Stop following the contract and every account. |
104
- | events | `change`, `frozen`, `config`, `market` (`{market, created}`), `connection`, `ledger` |
105
-
106
- | `AxisMarket` | Description |
107
- |---|---|
108
- | `base`, `quote`, `key`, `created`, `refreshed` | Canonical assets (the contract's `base` and `quote`), the `base/quote` key and oracle check times. |
109
- | `requote(signer?)` | Re-check the market against the oracle and cache prices (submits nothing when nothing changed). |
110
- | `subsidize({amount, sponsor?, signer?})` | Extend the oracle feeds access of the market. |
111
- | `getDepth({base?, depth?, step?, limit?})`, `subscribeDepth({base?, depth?, step?, limit?}, cb)` | Orderbook depth in the requested orientation, levels on multiples of `step`, pushed on book changes. |
112
- | `subscribeTrades(cb)` | Recent trades, then each new fill. |
113
- | `subscribeCandles({base?, resolution, limit?}, cb)` | Latest candles in the requested orientation (`limit`, default and max 200), then each candle changed by new trades. |
114
-
115
- | `AxisAccount` | Description |
116
- |---|---|
117
- | `orders`, `backing`, `ready`, `loaded` | Open orders by id and backing by token, in memory. |
118
- | `approvalTtl` | Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default). |
119
- | `balances`, `getBalance(asset)`, `funded` | Spendable balances by token (every market token), whether the account exists. |
120
- | `getOrders({market?, selling?, buying?})` | Open orders, newest first, including `pending` ones this client created. |
121
- | `getOrder(id)`, `committed(asset)`, `getAllowance(asset)` | Order lookup, open amount selling a token, allowance summary. |
122
- | `sell(params)`, `buy(params)` | Trade (`{selling, buying, amount, price?, kind?, expires?, orders?, approve?}`); without `price` it is a market order. Without `orders`, a limit order crosses the orders a direct quote finds up to its price (partial crossings included) and rests with the remainder; a market order crosses the quote for the full amount. Returns `{sold, bought, orderId?, order?, approve?}`. |
123
- | `estimateSell(params)`, `estimateBuy(params)` | Simulate the same trade without signing or submitting it. Returns `{fee, inclusionFee, resourceFee, sold, bought, orderId?}` (fees in stroops, `fee` is the maximum total). |
124
- | `update(updates)` | Change orders (omitted fields keep their values). |
125
- | `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of 100). |
126
- | `crossfill(takerOrderId, orders?)` | Fill an open order against the book. |
127
- | `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best AXIS API route. |
128
- | events | `ready`, `new`, `pending`, `fill`, `filled`, `update`, `cancel`, `expire`, `remove`, `order`, `backing`, `approve`, `trade`, `swap`, `change`, `error` |
129
-
130
- ## AxisContractClient
131
-
132
- Wraps the on-chain AXIS smart contract for trading and order management.
133
-
134
- ```js
135
- import {Networks, rpc} from '@stellar/stellar-sdk'
136
- import {AxisContractClient, OrderKind, TradeDirection} from '@axis-markets/client'
137
-
138
- const rpcUrl = 'https://soroban-testnet.stellar.org'
139
- const client = new AxisContractClient({
140
- publicKey: 'G...', // trader public key
141
- contractId: 'CBJ747MKAGQO2LMJPOTCOONAWBLIIBSLOQE325R457TE5MIS6RTDJ4DC', // AXIS contract (testnet)
142
- rpcUrl, // Stellar RPC server
143
- networkPassphrase: Networks.TESTNET, // Pubnet by default
144
- signTransaction: async (xdr, opts) => wallet.signTransaction(xdr, opts) // resolves to {signedTxXdr}
145
- })
146
- const {sequence} = await new rpc.Server(rpcUrl).getLatestLedger()
147
-
148
- // Place a sell limit order (the remainder becomes a limit order if not fully executed).
149
- // The id of the created order, if any, is returned as the third tuple element.
150
- const [sold, bought, newOrderId] = await client.sell({
151
- kind: OrderKind.Limit,
152
- trader: 'G...',
153
- amount: 100_000_000n, // 10 XLM
154
- selling: 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC', // XLM
155
- buying: 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA', // USDC
156
- price: 5n * 10n ** 17n, // at least 0.5 USDC per XLM (18 decimals)
157
- orders: [], // maker order ids to cross first (from a direct AXIS API quote)
158
- expires: Math.floor(Date.now() / 1000) + 86_400, // optional expiration of the created order (UNIX seconds)
159
- approve: {amount: 100_000_000n, liveUntil: sequence + 518_400} // optional in-call allowance on `selling` (~30 days)
160
- })
161
-
162
- // Fetch an order by id
163
- const order = await client.order(newOrderId)
164
-
165
- // Re-price an order in place (and keep it for another week)
166
- await client.update({
167
- trader: 'G...',
168
- updates: [{
169
- id: newOrderId,
170
- amount: 50_000_000n,
171
- price: 51n * 10n ** 16n, // 0.51 USDC per XLM
172
- expires: Math.floor(Date.now() / 1000) + 7 * 86_400
173
- }]
174
- })
175
-
176
- // Cancel orders (an `update` with a zero amount under the hood)
177
- await client.cancel('G...', [newOrderId])
178
- ```
179
-
180
- See [`src/index.d.ts`](src/index.d.ts) for the full typed API.
181
-
182
- ### Methods
183
-
184
- | Method | Description |
185
- |---|---|
186
- | `order(id)` | Fetch an order by id from on-chain storage. Returns `Promise<Order \| undefined>` (`undefined` for a missing or expired order). |
187
- | `loadConfig()` | Fetch the contract configuration (contract `config`). Returns `Promise<Config>`. |
188
- | `isFrozen()` | Whether the contract is frozen, trading and order management operations blocked (contract `frozen`). Returns `Promise<boolean>`. |
189
- | `getMarket(selling, buying)` | Fetch the market record for an asset pair, either order (contract `market`). Returns `Promise<Market \| undefined>`. |
190
- | `buy(params)` | Trade with the DEX and create a buy limit order if the quote is not fully executed (`params: BuyTradeArguments`). Returns `Promise<[sold, bought, newOrderId \| undefined]>`. |
191
- | `sell(params)` | Trade with the DEX and create a sell limit order if the quote is not fully executed (`params: SellTradeArguments`). Returns `Promise<[sold, bought, newOrderId \| undefined]>`. |
192
- | `estimateBuy(params)`, `estimateSell(params)` | Simulate `buy`/`sell` without signing or submitting, to show the network fee first. Returns `Promise<TradeEstimate>`: `fee` (maximum total, stroops), `inclusionFee`, `resourceFee` (including the rent of a new order), and the expected `sold`, `bought` and `orderId`. |
193
- | `update(params)` | Change the amount, the price and the expiration of several orders in place or remove them (zero `amount`), and optionally set allowances; missing orders are skipped, expired ones are revived, and an updated order's entry lifetime is extended to cover its expiration +1 day (`params: UpdateArguments`). Approvals and removals work in a frozen contract; up to 90 orders per. Returns `Promise<bigint[]>` with the ids updated or removed. |
194
- | `cancel(trader, ids)` | Cancel existing orders, expired ones included (`trader` is the owner address; `ids` is a `bigint[]`, non-existent orders are ignored). Client sugar: the contract has no `cancel`, this calls `update` with a zero amount per id; up to 90 orders per call. |
195
- | `crossfill(trader, takerOrderId, orders)` | Fill an existing order against matching orders from the book; profits from price inefficiencies (the crossed spread) go to `trader`. Returns `Promise<[sold, bought, surplus]>`: the amount the taker order sold, the amount it received and the surplus paid to `trader`. |
196
- | `swap(params)` | Swap tokens across several markets along a route (`params: SwapArguments`); the contract holds the intermediate hop proceeds only within the call. Returns `Promise<[sold, bought]>`. |
197
- | `keepalive(days?)` | Extend the contract instance and code lifetime to `days` (30 by default, at most the network maximum)Days are converted into ledgers with the configured `Config.ledger_time` (5 seconds when it cannot be read). Anyone can send it, and it works while the contract is frozen. Other calls extend the contract only when less than 3 days are left. Returns `Promise<number>`, the ledger both entries live until. |
198
- | `requote(selling, buying)` | Re-check both market assets against the price oracle and cache fresh prices for trading; the market record and the cache are rewritten only when they change. When the simulation writes nothing (the market and the cached prices are current, or the oracle has no newer price), no transaction is submitted and the simulated record is returned. Permissionless, blocked while frozen. Returns `Promise<Market \| undefined>` with the updated record (`undefined` for an unknown pair). |
199
- | `subsidize(params)` | Extend the oracle price feeds access of a market, creating the market if it does not exist yet, by burning exactly `amount` XRF from the sponsor (`params: SubsidizeArguments`). Returns `Promise<bigint[]>` with the new expiration timestamps. |
200
-
201
- Standalone helper: `orderId(owner, nonce)` (see below).
202
-
203
- The safety admin entry points (`freeze`, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days`,
204
- `set_ledger_time`) are skipped: they are operated outside the client.
205
-
206
- The contract itself caps neither the fills of a trade nor the orders of an `update`, the limitations come from the
207
- network's per-transaction limits. A trade settles at most 20 maker orders (`MAX_FILLS`). Each listed order the contract
208
- skips adds a `skip` event, and every trade adds the transfer that forwards the makers' assets to the taker, so 20 fills
209
- leave room for up to 3 skipped orders. An `update` fits about 100 changes or removals. These numbers follow the network
210
- limits: when a protocol upgrade raises them, more fills and updates can fit in one transaction.
211
-
212
- ### Markets and prices
213
-
214
- A `Limit` trade needs an open market for its pair: without one it fails with `AssetsNotVerifiedByOracle` (`721`).
215
- `Fill`/`FillOrKill` trades and `swap` only cross existing orders and need no market. A market is opened only by
216
- `subsidize({sponsor, selling, buying, amount})` (either asset order opens the same market), which requires at least one
217
- of the assets to be quoted by the price oracle:
218
-
219
- - On a pair without a market, `amount` must cover `Config.market_listing_fee` (`InvalidAmount`, `706`, otherwise). The
220
- fee is burned through an oracle `track` call, and whatever is left of `amount` through a second one (skipped when
221
- nothing is left). The sponsor signs both `track` calls and their XRF `burn` sub-invocations and never burns more than
222
- `amount`.
223
- - On an existing market the whole `amount` extends the price feeds access of its quoted assets.
224
- - `selling` and `buying` must differ (`InvalidMatch`, `704`).
225
-
226
- The listing fee is derived: the contract computes it as `daily_fee × listing_min_days` from the oracle's daily
227
- fee, and `loadConfig()` returns both values. `listing_min_days` is 90 at deployment, and the safety admin can set it
228
- from 0 to 255 days. The fee pays one `track` call split across the listed assets, so at 90 days a pair with one listed
229
- asset gets 90 days of feed and a pair with both listed 45 days each.
230
-
231
- `buy`, `sell` and `update` never call the oracle. They value orders against the prices cached by `requote` and
232
- `subsidize`, on the selling asset when it is listed and priced and otherwise on the buying asset; no usable price on
233
- either listed asset (missing or older than 72 hours) fails with `AssetPriceOracleFetchFailed` (`722`). Keepers call
234
- `requote(base, quote)` periodically for every active market (permissionless, moves no funds, blocked while frozen).
235
- `update` cannot change an order of a market whose assets the oracle no longer quotes (`AssetsNotVerifiedByOracle`,
236
- `721`), but removing it still works.
237
-
238
- ### Order expiration
239
-
240
- `buy`/`sell` take an optional `expires` UNIX timestamp in seconds (0 or omitted means no expiration). It applies to the
241
- order created for the remainder of a `Limit` trade and must be in the future (`InvalidExpiration`, `707`); other kinds
242
- ignore it. An expired order is invisible to `order()`, skipped by matching and treated as gone by `crossfill` (as the
243
- taker), but it can still be cancelled (removed by `update`), and `update` revives it when given an `expires` of 0 or in
244
- the future. Its id becomes free again, so a new order with the same nonce overwrites it. No event is emitted when an
245
- order expires.
246
-
247
- ### Allowances
248
-
249
- The contract holds no user funds between calls. Every asset a trader sells through AXIS needs a standing allowance
250
- granted to the contract on the token (`approve(from = trader, spender = AXIS, amount, liveUntil)`). Fills are settled
251
- with `transfer_from`, the contract acting as the spender: each maker's asset goes to the contract, the taker pays each
252
- maker directly, and the contract forwards what the makers delivered to the taker in one transfer at the end. Orders on
253
- the book are backed by the owner's balance and allowance. Matching never removes, trims or limits an order.
254
-
255
- A listed order whose maker's backing left does not cover the fill, whose maker cannot receive the taker's asset (a
256
- missing or deauthorized trustline), or whose maker's asset cannot be collected is skipped and left unchanged, and a
257
- `skip` event names it. The order owner is the party at fault. In a `crossfill` the skipped order can be the taker
258
- order, whose owner cannot back it or be paid: the call then returns `[0n, 0n, 0n]`.
259
-
260
- A payment to a maker that fails (the taker cannot pay, or the maker cannot be credited although authorized, e.g. a
261
- full trustline) fails the whole call with the token's own error. The client throws it with `tokenError: true` and
262
- blames neither side.
263
-
264
- A taker who cannot receive the bought asset fails the call with `CannotReceive` (`708`).
265
- The contract cannot hold an asset whose issuer requires authorization (`AUTH_REQUIRED`) until the issuer authorizes
266
- it: buying such an asset fails with `IntermediaryCannotReceive` (`712`). Selling it needs no contract authorization.
267
- A `swap` is strict: any transfer that fails fails the whole call.
268
-
269
- Pass `approve: {amount, liveUntil}` to `buy`, `sell` or `swap` to grant (or reset) the allowance on the selling asset as
270
- part of the same transaction (set `asset` to approve another token). `update` takes a separate
271
- `approvals: [{asset, amount, liveUntil}]` list: each entry must name its asset, an asset without an entry keeps its
272
- current allowance, and a zero amount revokes. The amount is absolute, not a delta, so the signed authorization does not
273
- depend on ledger state; when several approvals name the same asset, the last one wins. `cancel` never moves tokens.
274
-
275
- ### Order IDs and nonces
276
-
277
- An order ID is chosen by the client through a `u64` nonce:
278
-
279
- ```
280
- id = u128::from_be_bytes(sha256(xdr(ScVec[owner: Address, nonce: u64]))[0..16])
281
- ```
282
-
283
- - `buy`/`sell` generate the nonce internally on every call (`Date.now() << 22 | 22 random bits`, fits `u64` until 2109);
284
- callers never supply one. The id of the order created for the remainder is returned by the call.
285
- - `orderId(owner, nonce)` computes the id locally for a known nonce. `buy`/`sell` use it to declare the new order entry
286
- in the footprint before the transaction is signed (see below); custom pipelines that pick their own nonce can use it
287
- the same way. The contract has no view for it.
288
- - A nonce must be unique among the owner's live orders: the contract rejects a duplicate with `OrderExists` (`711`,
289
- available as `error.code` on the thrown error). Retrying the call generates a fresh nonce.
290
-
291
- ### Types
292
-
293
- #### `OrderKind`
294
-
295
- Trading order type — instructions to the contract on how to execute the trade.
296
-
297
- | Value | Numeric | Description |
298
- |---|---|---|
299
- | `Limit` | `1` | Execute the trade, creating a limit order if not executed in full. |
300
- | `Fill` | `2` | Execute the trade without creating a limit order. |
301
- | `FillOrKill` | `3` | Execute the trade, fail if it cannot be executed in full. |
302
-
303
- #### `TradeDirection`
304
-
305
- Trade direction instructions.
306
-
307
- | Value | Numeric | Description |
308
- |---|---|---|
309
- | `Sell` | `1` | Sell a fixed amount of asset. |
310
- | `Buy` | `2` | Buy a fixed amount of asset. |
311
-
312
- #### `ClientInitializationParams`
313
-
314
- Parameters passed to the `AxisContractClient` constructor.
315
-
316
- | Property | Type | Description |
317
- |---|---|---|
318
- | `publicKey` | `string` | Public key of the account that will interact with the contract. |
319
- | `signTransaction` | `SignTransactionCallback` | Callback for signing transactions generated by the client. |
320
- | `rpcUrl` | `string` | URL of the RPC server. |
321
- | `contractId` | `string` | DEX contract id. |
322
- | `networkPassphrase?` | `string` | Network passphrase (Pubnet passphrase by default). |
323
- | `fee?` | `string` | Inclusion fee bid in stroops (`'100000'`, 0.01 XLM, by default). The resource fee from simulation is added on top. |
324
- | `autoFootprint?` | `boolean` | 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). |
325
-
326
- #### `SignTransactionCallback`
327
-
328
- `(xdr: string, opts?: {networkPassphrase?, address?, submit?, submitUrl?}) => Promise<{signedTxXdr, signerAddress?, error?}>`
329
-
330
- Callback for signing transactions generated by the client, in the `@stellar/stellar-sdk` 17 contract client shape. It
331
- receives the transaction XDR and the network passphrase, and resolves to the signed transaction XDR. Stellar Wallets
332
- Kit's
333
- `signTransaction` matches it (pass the connected `address` along), and a `Keypair` signer is a few lines:
334
- `TransactionBuilder.fromXDR(xdr, opts.networkPassphrase)`, `tx.sign(keypair)`, `{signedTxXdr: tx.toXDR()}`.
335
-
336
- #### `Approval`
337
-
338
- Token allowance granted to the contract as part of the call.
339
-
340
- | Property | Type | Description |
341
- |---|---|---|
342
- | `asset?` | `string` | Token the allowance is granted on: defaults to `selling` for `buy`, `sell` and `swap`, required in `update` approvals. |
343
- | `amount` | `bigint` | Absolute allowance amount (0 revokes the approval). |
344
- | `liveUntil` | `number` | Ledger sequence the allowance lives until (at most ~180 days ahead). |
345
-
346
- #### `TradeArguments`
347
-
348
- Base arguments shared by `buy` and `sell`.
349
-
350
- | Property | Type | Description |
351
- |---|---|---|
352
- | `kind` | `OrderKind` | Trading order behavior. |
353
- | `trader` | `string` | Trader address. |
354
- | `amount` | `bigint` | Tokens amount. |
355
- | `selling` | `string` | Selling token address. |
356
- | `buying` | `string` | Buying token address. |
357
- | `price` | `bigint` | Price a trader is willing to accept (18 decimals). |
358
- | `orders?` | `bigint[]` | List of order IDs to match before creating the order on-chain. |
359
- | `expires?` | `bigint \| number` | Expiration UNIX timestamp (seconds) of the order created for a `Limit` remainder, 0 or omitted = none. |
360
- | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
361
-
362
- #### `SellTradeArguments`
363
-
364
- Extends `TradeArguments` (passed to `sell`).
365
-
366
- | Property | Type | Description |
367
- |---|---|---|
368
- | `amount` | `bigint` | Amount of `selling` tokens to sell. |
369
- | `price` | `bigint` | Price a trader is willing to accept — minimum `buying` tokens per 1 `selling`. |
370
-
371
- #### `BuyTradeArguments`
372
-
373
- Extends `TradeArguments` (passed to `buy`).
374
-
375
- | Property | Type | Description |
376
- |---|---|---|
377
- | `amount` | `bigint` | Amount of `buying` tokens to acquire. |
378
- | `price` | `bigint` | Price a trader is willing to accept — maximum `selling` tokens per 1 `buying`. |
379
-
380
- #### `TradeStep`
381
-
382
- A trade step in a multi-market swap path.
383
-
384
- | Property | Type | Description |
385
- |---|---|---|
386
- | `asset` | `string` | Asset to buy at this step. |
387
- | `orders` | `bigint[]` | Maker order IDs to match. |
388
-
389
- #### `SwapArguments`
390
-
391
- Arguments passed to `swap`.
392
-
393
- | Property | Type | Description |
394
- |---|---|---|
395
- | `direction` | `TradeDirection` | Trade direction: `Sell` or `Buy`. |
396
- | `trader` | `string` | Trader address. |
397
- | `selling` | `string` | Token address sent by the trader. |
398
- | `sellingAmount` | `bigint` | Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`). |
399
- | `buyingAmount` | `bigint` | Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`). |
400
- | `path` | `TradeStep[]` | Ordered list of the trade route steps. |
401
- | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
402
-
403
- #### `UpdateArguments`
404
-
405
- | Property | Type | Description |
406
- |---|---|---|
407
- | `trader` | `string` | Orders owner. |
408
- | `updates` | `OrderUpdate[]` | New amount, price and expiration per order id. |
409
- | `approvals?` | `Approval[]` | Allowances granted before the backing check, each naming its `asset`; an asset without an approval keeps its current allowance. |
410
-
411
- #### `OrderUpdate`
412
-
413
- | Property | Type | Description |
414
- |---|---|---|
415
- | `id` | `bigint` | Order id. |
416
- | `amount` | `bigint` | New amount to sell, `0` removes the order. |
417
- | `price` | `bigint` | New order price (ignored for a removal). |
418
- | `expires?` | `bigint \| number` | New expiration UNIX timestamp (seconds), 0 or omitted = none. |
419
-
420
- #### `SubsidizeArguments`
421
-
422
- | Property | Type | Description |
423
- |---|---|---|
424
- | `sponsor` | `string` | Address paying for the oracle feeds (and the listing fee of a new market). |
425
- | `selling` | `string` | First market asset. |
426
- | `buying` | `string` | Second market asset (either order opens the same market). |
427
- | `amount` | `bigint` | Amount of XRF fee tokens to burn; at least `Config.market_listing_fee` to open a market. |
428
-
429
- #### `Order`
430
-
431
- Order properties, stored on-chain (returned by `order()` call).
432
-
433
- | Property | Type | Description |
434
- |---|---|---|
435
- | `id` | `bigint` | Order ID, derived from the owner and the client nonce. |
436
- | `owner` | `string` | Owner of the order. |
437
- | `selling` | `string` | Selling token address. |
438
- | `buying` | `string` | Buying token address. |
439
- | `amount` | `bigint` | Amount left to sell. |
440
- | `price` | `bigint` | Order price (`buying` per 1 `selling`, 18 decimals). |
441
- | `expires` | `bigint` | Expiration UNIX timestamp in seconds (0 = no expiration). |
442
-
443
- #### `Config`, `Market`, `MarketSide`
444
-
445
- Decoded straight from the contract, so field names keep the contract's snake_case:
446
- `Config {safety_admin, oracle, listing_min_days, market_listing_fee, min_trade_size, ledger_time}`,
447
- `Market {base, quote, created}` (the assets in canonical order, `created` in UNIX seconds),
448
- `MarketSide {asset, listed, decimals}`. `market_listing_fee` is derived from the oracle
449
- (`daily_fee × listing_min_days`), never supplied. The contract is deployed with
450
- `__constructor(safety_admin, oracle, min_trade_size)`, which sets
451
- `listing_min_days` to 90 and `ledger_time` (the ledger close time lifetimes are converted with) to 5 seconds. An asset
452
- whose token and oracle decimals add up to more than 37 is recorded as unlisted.
453
-
454
- ### Contract events
455
-
456
- Trading events use the `vec` data format: the event data is a vector of the fields in the order listed. There is no
457
- trade or swap id; indexers derive one from the ledger, transaction and event position.
458
-
459
- | Event | Topics | Data | Notes |
460
- |---|---|---|---|
461
- | `trade` | `trade, selling, buying` (assets sold and bought by the taker) | `order, taker, maker, sold, bought, left` | One per fill. `left` is the order amount after the fill, `0` when the order was filled in full (or what is left became dust) and removed. Fills emit no order event. In a `crossfill` the maker fills name the taker order owner as the taker, and a last event reports the taker order fill with the caller as the taker. |
462
- | `swap` | `swap, selling, buying` | `trader, sold, bought` | One per `swap` call, after the fills of every hop. |
463
- | `new` | `new, selling, buying` | `id, owner, price, amount, expires` | An order created. `id` is a `u128`, `expires` a `u64` (0 = none). |
464
- | `mod` | `mod` | `id, price, amount, expires` | An order changed outside a fill: `update` (new price, amount and expiration) or removal by `update`/`cancel` (`amount = 0`). Nothing is emitted when an order expires. |
465
- | `skip` | `skip` | `order: u128` | A listed order its maker could not settle (backing short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected). The order is left unchanged. Also a `crossfill` taker order its owner cannot back or be paid for. |
466
- | `refresh` | `refresh, base, quote` (market assets in canonical order) | none | Every check of a market against the oracle (`requote`, `subsidize`, market creation). |
467
- | `freeze` | `freeze` | `frozen: bool` | |
468
- | `config` | `config` | `Config` | The configuration after the constructor, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days` or `set_ledger_time`. |
469
-
470
- Typed as `TradeContractEvent`, `SwapContractEvent`, `OrderCreatedContractEvent`, `OrderUpdatedContractEvent`,
471
- `OrderSkippedContractEvent`, `MarketRefreshContractEvent`, `FreezeContractEvent`, `ConfigChangedContractEvent` in
472
- [`src/index.d.ts`](src/index.d.ts).
473
-
474
- ### Contract errors
475
-
476
- Simulation failures caused by the contract are thrown as `Error` with `message` `Contract execution error: #<code>
477
- <name>` and a numeric `code` property. A failure raised by a token the call invoked (a settlement transfer) is thrown as
478
- an `Error` with the token's `code`, `tokenError: true` and the token `contract`, named after `TokenErrors` (for example
479
- `#10 BalanceError`, which a payer without the balance and a recipient at its trustline limit both raise). Other
480
- simulation failures are rethrown as the raw RPC error string, not an `Error`. A transaction that passes simulation but
481
- fails on-chain throws an `Error` with the transaction `hash` property and the transaction result in its `message`.
482
- `ContractErrors` maps the codes:
483
-
484
- | Code | Name | Meaning |
485
- |---|---|---|
486
- | 701 | `NotAuthorized` | An `update` or `cancel` lists an order that `trader` does not own. |
487
- | 702 | `InsufficientBalance` | The order is not backed by the trader's balance. |
488
- | 703 | `InsufficientAllowance` | The allowance granted to the contract does not cover the order. |
489
- | 704 | `InvalidMatch` | `selling` equals `buying` (trades and `subsidize`), or a `swap` has no path or a non-positive amount (a listed order of another pair is skipped, not an error). |
490
- | 705 | `InvalidPrice` | Price outside `[1, 10^36]`. |
491
- | 706 | `InvalidAmount` | An amount is not positive, a `subsidize` that opens a market is below the listing fee, or a configuration value is out of range. |
492
- | 707 | `InvalidExpiration` | An `expires` is neither 0 nor in the future. |
493
- | 708 | `CannotReceive` | The trader cannot receive the bought asset: a missing or deauthorized trustline, or a full one (the transfer forwarding the makers' assets failed). Never a maker's fault. |
494
- | 709 | `NotFilled` | A `FillOrKill` trade or `swap` cannot be executed in full. |
495
- | 710 | `OrderNotFound` | The order does not exist or has expired. |
496
- | 711 | `OrderExists` | A live order with the same id exists (retry the call). |
497
- | 712 | `IntermediaryCannotReceive` | The contract cannot hold an asset it passes on: the asset requires issuer authorization and the issuer has not authorized the AXIS contract yet. |
498
- | 720 | `OrderSizeTooSmall` | Order value below the minimum order size, or the remainder is dust. |
499
- | 721 | `AssetsNotVerifiedByOracle` | The pair has no market (open it with `subsidize`), or neither asset is listed on the price oracle (a `Limit` trade, an `update` that changes an order, `subsidize`). |
500
- | 722 | `AssetPriceOracleFetchFailed` | No listed market asset has a usable cached price (none cached within the last 72 hours). |
501
- | 723 | `InvalidOracleConfig` | The price oracle does not satisfy the contract requirements (at most 24 decimals, a daily fee). |
502
- | 730 | `Frozen` | Trading is blocked (order removals and approvals still work). |
503
- | 740 | `Overflow` | An arithmetic invariant was violated. Other arithmetic overflows trap as a host error. |
504
-
505
- ## AxisApiClient
506
-
507
- HTTP client for the AXIS REST API. Uses the standard `fetch` API - no extra dependencies.
508
-
509
- ```js
510
- import {AxisApiClient, AxisApiError} from '@axis-markets/client'
511
-
512
- const api = new AxisApiClient('https://demo-api.axis.markets') // testnet
513
- const USDC = 'USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' // testnet USDC
514
-
515
- // Quote: sell a fixed amount of the source asset (strict send)
516
- const sellQuote = await api.quoteSell({
517
- sellingAsset: 'XLM',
518
- buyingAsset: USDC,
519
- amount: '10000000' // stroops (1 unit = 10,000,000 stroops)
520
- })
521
- if (sellQuote.status !== 'success') {
522
- console.log(sellQuote.error) // 'unfeasible' (not enough liquidity) or 'rejected' (contract frozen, or an asset the contract cannot hold)
523
- }
524
-
525
- // Quote: buy a fixed amount of the destination asset (strict receive)
526
- const buyQuote = await api.quoteBuy({
527
- sellingAsset: 'XLM',
528
- buyingAsset: USDC,
529
- amount: '5000000'
530
- })
531
-
532
- // Order book depth around the mid price
533
- const depth = await api.getDepth({market: `XLM/${USDC}`, depth: 20})
534
-
535
- // OHLCVT candles of the last week
536
- const candles = await api.getCandles({
537
- market: `XLM/${USDC}`,
538
- from: Math.floor(Date.now() / 1000) - 7 * 86_400, // UNIX seconds, the window starts at 0 (1970) without it
539
- resolution: '1h',
540
- order: 'asc'
541
- })
542
-
543
- // 24h ticker for every market
544
- const {ticker} = await api.getTicker24h()
545
- ```
546
-
547
- ### AxisApiClient Methods
548
-
549
- | Method | Description |
550
- |---|---|
551
- | `quoteSell({sellingAsset, buyingAsset, amount, direct?, maxPrice?})` | Best trade routes for selling a fixed amount of the source asset (strict send). Each hop lists the matched order ids and `worstPrice` (a trade limit that crosses every listed order). Without enough liquidity it resolves with `status: 'unfeasible'` and an `error`, and while the contract is frozen with `status: 'rejected'`. It throws `AxisApiError` with status 409 when the server is not ready or routing fails, and 400 for invalid parameters. With `direct` and `maxPrice` (the highest maker price to cross, in `worstPrice` units) it quotes the crossing of a limit order: orders priced above the limit are left out and the route may trade less than `amount`. |
552
- | `quoteBuy({sellingAsset, buyingAsset, amount, direct?, maxPrice?})` | Best trade routes for buying a fixed amount of the destination asset (strict receive). Resolves and throws like `quoteSell`. |
553
- | `getDepth({market, depth?, step?, limit?})` | Order book depth around the mid price (`depth` is the ± band %, 0–100, default 20) in price levels on multiples of `step` (e.g. `"0.0005"`; 5 significant digits by default), `limit` levels per side (default 100). Bids are rounded down and asks up, so a level price crosses every order in it; `bestBid`/`bestAsk` are the exact best prices. |
554
- | `getCandles({market, from?, to?, resolution?, order?})` | OHLCVT candlestick data. `resolution` accepts seconds or an alias (`5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `12h`, `1d`, `3d`, `1w`, `2w`; default `auto`). |
555
- | `getTicker24h()` | 24-hour ticker statistics for every available market. |
556
- | `getMarkets({cursor?, limit?})` | Pairs with orders on the book, with pagination (cached for up to 30 minutes). Markets opened on-chain come from `getContract()`. |
557
- | `getContract()` | Contract state tracked by the indexer: contract `address`, `frozen`, `config` (`safetyAdmin`, `oracle`, `listingMinDays`, `marketListingFee`, `minTradeSize`, `ledgerTime`) and active `markets` (`base`, `quote`, `created`, `refreshed`). |
558
- | `getOrders({owner?, asset?, cursor?, limit?})` | Active orders, filterable by owner or asset (`asset` may be a string or string array). |
559
- | `getOrder(id)` | A single active order by ID (throws `AxisApiError` with status 404 if not found). |
560
- | `getAccount(address)` | Every live order of an account (not paginated) and its backing per traded token. |
561
- | `getOrderHistory({owner?, pair?, cursor?, limit?})` | Archived/historical orders, newest first (`pair` = `[base, quote]` contract ids). |
562
- | `getTrades({trader?, pair?, cursor?, limit?})` | Recent trades and swaps, newest first (`type: 'trade' \| 'swap'`, `pair` = `[base, quote]` contract ids). The fill of a `crossfill` taker order carries `crossfill: true`: its `taker` is the caller paid the surplus, and the aggregator leaves it out of candles and volume. |
563
- | `getFailures({account?, fn?, cursor?, limit?})` | Failed AXIS calls, newest first (diagnostics only): calls made by the transaction or through another contract, in failed transactions or caught by a calling contract (`caught`). `account` matches the caller and both parties of a failed transfer. Each record has a `reason` (`contract`, `transfer`, `resources`, `auth`, `unknown`), the contract `error` and the failed `transfer`. A record never blames a party: a failed transfer names both sides. |
564
-
565
- Classic asset strings (`XLM`, `CODE:Issuer`, `CODE-Issuer`) are accepted by `quoteSell`, `quoteBuy`, `getDepth` and
566
- `getCandles`, next to Soroban contract ids. The `asset`, `pair` and `owner` filters of the order and trade lists need
567
- contract ids and account addresses. Markets use the `BASE/QUOTE` convention, each side in any of these formats. Amounts
568
- are expressed in stroops on input and returned as strings. Orders, trades and quotes carry raw integer amounts and
569
- 18-decimal contract prices, while `getDepth`, `getCandles` and `getTicker24h` return decimal prices and whole-unit
570
- volumes. Order ids are decimal strings of the `u128` id. They are not sequential, so pagination passes the `cursor`
571
- field of the last received row (the creation position of an order, the id of a trade), not the id. Orders carry `backed`
572
- (the amount the maker can actually deliver) and `backing` when the indexer tracks maker balances and allowances. Account
573
- backing records also carry `headroom` in the assets the account receives: the room left under its trustline limit
574
- (omitted when unlimited or unknown).
575
-
576
- ### Error handling
577
-
578
- Non-success responses throw an `AxisApiError` carrying the HTTP `status` code:
579
-
580
- ```js
581
- try {
582
- await api.getOrder('123')
583
- } catch (e) {
584
- if (e instanceof AxisApiError && e.status === 404) {
585
- // not found
586
- }
587
- throw e
588
- }
589
- ```
590
-
591
- ## Order footprint
592
-
593
- Soroban RPC simulation records only the ledger entries the contract actually touched against the state at simulation
594
- time. The orderbook matching loop stops as soon as the taker is filled, and orders it skipped are recorded read-only
595
- without their makers' entries. If the book moves before the transaction lands - an order is partly filled, repriced back
596
- into range, its maker restores the backing, an earlier order shrinks, or an expired order is revived - the contract has
597
- to read and write entries that are missing from the footprint, resulting in a rejection. Likewise, a `Limit` trade that
598
- simulation filled in full may create an order for a remainder at apply time under an entry the simulation never saw.
599
-
600
- To make trading transactions resilient to such changes, `buy`, `sell`, `crossfill` and `swap` patch the simulated
601
- transaction before signing. Every order id passed in `orders` (plus the taker order id for `crossfill`, every path step
602
- for `swap`, and the remainder id `orderId(trader, nonce)` for `Limit` trades) is declared in the read-write footprint,
603
- and so are the entries the settlement of the call writes whatever makers fill: the contract's own balance of every asset
604
- passing through it (the bought asset, every hop asset of a `swap`, the asset a `crossfill` taker order buys) and the
605
- receiver's balance of the bought asset. Then every entry the settlement may write for the maker behind each listed
606
- order: the balance of the asset the maker sells, the maker's allowance on it to the contract, and the balance of the
607
- asset the maker receives (an account entry for XLM, a trustline for a classic asset, the token's `Balance` entry for a
608
- contract address, none for the asset issuer). The client loads the listed orders and the token instances with one RPC
609
- `getLedgerEntries` call (the classic asset behind each token is cached per client) and adds entries in that order while
610
- the footprint limits (200 read-write, 400 total) allow. Tokens that are not Stellar Asset Contracts keep what the
611
- simulation recorded: their storage layout is unknown. The declared instructions, write bytes and resource fee grow with
612
- every added entry, and the disk read bytes with every added account or trustline entry the simulation did not read; the
613
- surplus resource fee is refundable, but every declared read-write entry pays the write-entry fee, so routers should list
614
- only orders they expect to fill. `update` declares the updated order ids only. Pass `autoFootprint: false` to the
615
- constructor to opt out.
616
-
617
- Order entries are keyed by the raw `u128` order id in persistent contract storage and hold a positional vector
618
- `[owner, selling, buying, amount, price, expires?]`. The helpers exported for custom pipelines:
619
-
620
- ```js
621
- import {orderId} from '@axis-markets/client'
622
- import {collectOrderIds, completeFootprint} from '@axis-markets/client/footprint'
623
- import {rpc} from '@stellar/stellar-sdk'
624
-
625
- // the raw `trade` entry point takes the nonce explicitly - any u64 unique among the owner's live orders
626
- const nonce = (BigInt(Date.now()) << 22n) | BigInt(crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff)
627
- const tx = await client.client.trade({...payload, nonce, expires: 0n}, {fee})
628
- await completeFootprint(tx, contractId, collectOrderIds(payload.orders, [orderId(payload.trader, nonce)]), {
629
- server: new rpc.Server(rpcUrl),
630
- tokens: [payload.selling, payload.buying],
631
- passThrough: [payload.buying], // makers deliver to the contract
632
- receiver: payload.trader, // which forwards to the trader
633
- bought: payload.buying
634
- })
635
- await tx.signAndSend()
636
- ```
637
-
638
- `ensureOrdersFootprint(tx, contractId, orderIds)` declares the order entries alone (no RPC call), and
639
- `orderLedgerKey`, `balanceLedgerKey`, `allowanceLedgerKey`, `instanceLedgerKey`, `decodeStoredOrder` and
640
- `decodeSacAsset` build and decode the individual entries.
641
-
642
- ## Development
643
-
644
- Run tests:
645
-
646
- ```
647
- pnpm test
648
- ```
649
-
650
- Bundling script:
651
-
652
- ```
653
- pnpm run prepare
654
- ```
655
-
656
- Bundles the ESM source (`src/`) into a UMD library (`lib/`) via webpack. Type definitions located in `src/index.d.ts`.
657
-
658
- ## License
659
-
660
- MIT
1
+ # @axis-markets/client
2
+
3
+ JavaScript SDK for [AXIS](https://axis.markets) Stellar DEX.
4
+
5
+ - **`Axis`**, **`AxisMarket`**, **`AxisAccount`** - high-level API stateful: the DEX state (contract, markets) and a
6
+ trader's open orders and allowances kept in memory from the AXIS API WebSocket push channel, with trading calls that
7
+ look up the crossing orders and manage allowances automatically.
8
+ - **`AxisContractClient`** — wraps the on-chain AXIS smart contract for order management and trading (sign & send
9
+ transactions, read orders, markets and configuration).
10
+ - **`AxisApiClient`** - a dependency-free HTTP client for the AXIS REST API (quotes, orderbook depth, candles, ticker,
11
+ market/order/trade data).
12
+ - **`AxisStreamClient`** - WebSocket client of the AXIS API push channel.
13
+
14
+ ## Installation
15
+
16
+ ```
17
+ npm i @axis-markets/client
18
+ ```
19
+
20
+ Requires Node.js 22+ (or any modern browser). `@stellar/stellar-sdk` 17+ is a peer dependency (v17 changed the XDR
21
+ representation and is not source-compatible with v16).
22
+
23
+ ## Axis — high-level API
24
+
25
+ `Axis` wrapper follows the contract state (frozen switch, configuration) and every market through the AXIS API push API,
26
+ falling back to REST polling while the push connection is down. `axis.account()`
27
+ returns an `AxisAccount` that keeps in memory all open orders of a trader across every market, and the trader's
28
+ spendable balance and allowance in every market token, and trades with automatic allowance management. The AXIS API's
29
+ data source streams updates for that state to maintain consistent up-to-date state in memory.
30
+
31
+ The samples use the Testnet AXIS API (`https://demo-api.axis.markets`, push API at `wss://demo-api.axis.markets/ws`)
32
+ and the Testnet tokens below.
33
+
34
+ ```js
35
+ import {Axis, TradeDirection} from '@axis-markets/client'
36
+
37
+ //testnet token contracts
38
+ const XLM = 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC'
39
+ const USDC = 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA'
40
+ const EURC = 'CCUUDM434BMZMYWYDITHFXHDMIVTGGD6T2I5UKNX5BSLXLW7HVR4MCGZ'
41
+
42
+ const axis = new Axis({
43
+ apiUrl: 'https://demo-api.axis.markets',
44
+ rpcUrl: 'https://soroban-testnet.stellar.org',
45
+ networkPassphrase: 'Test SDF Network ; September 2015'
46
+ })
47
+ await axis.connect() // the contract address comes from the AXIS API
48
+ axis.on('frozen', frozen => console.log('trading', frozen ? 'suspended' : 'resumed'))
49
+
50
+ const market = axis.getMarket(XLM, USDC) // either order: market.base / market.quote are in the contract order
51
+
52
+ const account = axis.account(publicKey, {signTransaction})
53
+ await account.ready
54
+ account.on('fill', ({order, sold, bought}) => console.log(`order ${order.id}: sold ${sold}, got ${bought}`))
55
+ account.on('filled', ({order}) => console.log(`order ${order.id} filled`))
56
+ account.on('expire', order => console.log(`order ${order.id} expired`))
57
+ account.on('backing', ({asset}) => console.log(asset, 'balance', account.getBalance(asset)))
58
+
59
+ // network fee of the trade before signing anything (a simulation with the same crossing and approval)
60
+ const {fee} = await account.estimateSell({selling: XLM, buying: USDC, amount: 1_000_000_000n, price: 25n * 10n ** 16n})
61
+ // limit sell of 100 XLM at 0.25 USDC; crossing orders and the approval are handled by the account
62
+ const {sold, bought, orderId} = await account.sell({
63
+ selling: XLM,
64
+ buying: USDC,
65
+ amount: 1_000_000_000n,
66
+ price: 25n * 10n ** 16n
67
+ })
68
+ // market buy of 10 XLM (no price: crosses the book at the worst quoted maker price)
69
+ await account.buy({selling: USDC, buying: XLM, amount: 100_000_000n})
70
+ await account.update([{id: orderId, amount: 500_000_000n}])
71
+ await account.cancelAll({market})
72
+ await account.swap({selling: USDC, buying: EURC, amount: 10_000_000n, direction: TradeDirection.Sell, slippage: 0.005})
73
+ ```
74
+
75
+ **Allowances.** The contract holds no funds: an order is fillable up to `min(balance, allowance)` in the sold token, and
76
+ one allowance record backs every order selling it. Before each `sell`, `buy`, `swap` and a growing `update`, the account
77
+ checks the allowance and attaches to cover all active orders. An `update` that does not grow its orders still raises an
78
+ allowance that does not back them (the contract would reject it). `cancel`, `cancelAll` and a shrinking `update` lower
79
+ the allowance to what the remaining open orders selling the token need, and to zero when none remain. With more than one
80
+ batch, each batch carries the allowance its orders need, so a declined signature leaves the rest backed.
81
+ `revoke(assets, {cancelOrders?})` sets allowances to zero, optionally canceling the orders selling them in the same
82
+ transactions. A new allowance lives `account.approvalTtl` ledgers (`APPROVAL_TTL_LEDGERS`, ~180 days, unless set with
83
+ `axis.account(address, {approvalTtl})`), at most `MAX_APPROVAL_TTL_LEDGERS`. A fill lowers the allowance and the order
84
+ it fills in the same pushed ledger, so the memory state stays consistent. The allowance is read over RPC only when the
85
+ push connection is down, the token is not tracked, for 30 s after this client spent the token as a taker (the push
86
+ reporting the spend may lag behind), and after this client set it until the push reports the change (at most 6 minutes).
87
+ An order this client created counts as committed right away (`pending: true`) until the indexer reports it, and an order
88
+ it changed or canceled shows the change right away.
89
+
90
+ **One call at a time.** Calls that submit transactions (`sell`, `buy`, `swap`, `update`, `cancel`, `cancelAll`,
91
+ `revoke`, `crossfill`) run one after another: each one builds its transaction, which fixes its sequence number, and
92
+ plans its approvals only after the previous one settled. Concurrent calls of an account therefore never fail with
93
+ `tx_bad_seq` against each other.
94
+
95
+ **Balances.** While an account is subscribed, the AXIS API tracks it in every market token.
96
+ `account.balances` / `getBalance(asset)` give the spendable amount, and each change emits
97
+ `backing` event.
98
+
99
+ **Backing.** Each `AccountOrder` carries `backed` (its share of the budget, split by the indexer among the orders
100
+ selling the token oldest first), `backedPct` and `backingPending`.
101
+ `account.getAllowance(asset)` reports `balance`, `allowance`, `liveUntil`, `available` and `committed`.
102
+
103
+ | `Axis` | Description |
104
+ |---|---|
105
+ | `connect()` | Load the contract state and follow its changes. |
106
+ | `contractId`, `getContractId()` | AXIS contract address. |
107
+ | `ledger`, `getLedger()` | Last ledger pushed by the AXIS API; current ledger (pushed, or RPC when stale). |
108
+ | `frozen`, `config`, `markets`, `loaded` | Contract state; `markets` is a `Map` of `AxisMarket` by canonical key. |
109
+ | `getMarket(x, y)` | Market of the asset pair in either order, `undefined` if not open. |
110
+ | `getOrder(id)` | Live order from a tracked account's memory or the AXIS API, `undefined` if gone. |
111
+ | `account(address, {signTransaction, approvalTtl?})` | `AxisAccount` of the trader (one per address), `approvalTtl` sets the lifetime of the allowances it grants in ledgers. |
112
+ | `subscribeTicker(cb)` | 24h ticker of every market (canonical orientation); also fills `market.ticker`. |
113
+ | `keepalive({days?, signer?})` | Extend the contract instance and code lifetime, see `AxisContractClient.keepalive`. |
114
+ | `close()` | Stop following the contract and every account. |
115
+ | events | `change`, `frozen`, `config`, `market` (`{market, created}`), `connection`, `ledger` |
116
+
117
+ | `AxisMarket` | Description |
118
+ |---|---|
119
+ | `base`, `quote`, `key`, `created`, `refreshed` | Canonical assets (the contract's `base` and `quote`), the `base/quote` key and oracle check times. |
120
+ | `requote(signer?)` | Re-check the market against the oracle and cache prices (submits nothing when nothing changed). |
121
+ | `subsidize({amount, sponsor?, signer?})` | Extend the oracle feeds access of the market. |
122
+ | `getDepth({base?, depth?, step?, limit?})`, `subscribeDepth({base?, depth?, step?, limit?}, cb)` | Orderbook depth in the requested orientation, levels on multiples of `step`, pushed on book changes. |
123
+ | `subscribeTrades(cb)` | Recent trades, then each new fill. |
124
+ | `subscribeCandles({base?, resolution, limit?}, cb)` | Latest candles in the requested orientation (`limit`, default and max 200), then each candle changed by new trades. |
125
+
126
+ | `AxisAccount` | Description |
127
+ |---|---|
128
+ | `orders`, `backing`, `ready`, `loaded` | Open orders by id and backing by token, in memory. |
129
+ | `approvalTtl` | Lifetime of the allowances granted by trading calls, in ledgers (`APPROVAL_TTL_LEDGERS` by default, at most `MAX_APPROVAL_TTL_LEDGERS`). |
130
+ | `balances`, `getBalance(asset)`, `funded` | Spendable balances by token (every market token), whether the account exists. |
131
+ | `getOrders({market?, selling?, buying?})` | Open orders, newest first, including `pending` ones this client created. |
132
+ | `getOrder(id)`, `committed(asset)`, `getAllowance(asset)` | Order lookup, open amount selling a token, allowance summary. |
133
+ | `sell(params)`, `buy(params)` | Trade (`{selling, buying, amount, price?, kind?, expires?, orders?, approve?}`); without `price` it is a market order. Without `orders`, a limit order crosses the orders a direct quote finds up to its price (partial crossings included) and rests with the remainder; a market order crosses the quote for the full amount. Returns `{sold, bought, orderId?, order?, approve?}`. |
134
+ | `estimateSell(params)`, `estimateBuy(params)` | Simulate the same trade without signing or submitting it. Returns `{fee, inclusionFee, resourceFee, sold, bought, orderId?}` (fees in stroops, `fee` is the maximum total). |
135
+ | `update(updates)` | Change orders (omitted fields keep their values), raising or lowering the allowance to what the open orders need. |
136
+ | `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of up to 90) and lower the allowance to what the remaining orders need. |
137
+ | `revoke(assets, {cancelOrders?})` | Set the allowances on the tokens to zero, optionally canceling the orders selling them. Returns `{revoked, canceled}`. |
138
+ | `crossfill(takerOrderId, orders?)` | Fill an open order against the book. |
139
+ | `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best AXIS API route. |
140
+ | events | `ready`, `new`, `pending`, `fill`, `filled`, `update`, `cancel`, `expire`, `remove`, `order`, `backing`, `approve`, `trade`, `swap`, `change`, `error` |
141
+
142
+ ## AxisContractClient
143
+
144
+ Wraps the on-chain AXIS smart contract for trading and order management.
145
+
146
+ ```js
147
+ import {Networks, rpc} from '@stellar/stellar-sdk'
148
+ import {AxisContractClient, OrderKind, TradeDirection, APPROVAL_TTL_LEDGERS} from '@axis-markets/client'
149
+
150
+ const rpcUrl = 'https://soroban-testnet.stellar.org'
151
+ const client = new AxisContractClient({
152
+ publicKey: 'G...', // trader public key
153
+ contractId: 'CBJ747MKAGQO2LMJPOTCOONAWBLIIBSLOQE325R457TE5MIS6RTDJ4DC', // AXIS contract (testnet)
154
+ rpcUrl, // Stellar RPC server
155
+ networkPassphrase: Networks.TESTNET, // Pubnet by default
156
+ signTransaction: async (xdr, opts) => wallet.signTransaction(xdr, opts) // resolves to {signedTxXdr}
157
+ })
158
+ const {sequence} = await new rpc.Server(rpcUrl).getLatestLedger()
159
+
160
+ // Place a sell limit order (the remainder becomes a limit order if not fully executed).
161
+ // The id of the created order, if any, is returned as the third tuple element.
162
+ const [sold, bought, newOrderId] = await client.sell({
163
+ kind: OrderKind.Limit,
164
+ trader: 'G...',
165
+ amount: 100_000_000n, // 10 XLM
166
+ selling: 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC', // XLM
167
+ buying: 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA', // USDC
168
+ price: 5n * 10n ** 17n, // at least 0.5 USDC per XLM (18 decimals)
169
+ orders: [], // maker order ids to cross first (from a direct AXIS API quote)
170
+ expires: Math.floor(Date.now() / 1000) + 86_400, // optional expiration of the created order (UNIX seconds)
171
+ approve: {amount: 100_000_000n, liveUntil: sequence + APPROVAL_TTL_LEDGERS} // optional in-call allowance on `selling` (~180 days)
172
+ })
173
+
174
+ // Fetch an order by id
175
+ const order = await client.order(newOrderId)
176
+
177
+ // Re-price an order in place (and keep it for another week)
178
+ await client.update({
179
+ trader: 'G...',
180
+ updates: [{
181
+ id: newOrderId,
182
+ amount: 50_000_000n,
183
+ price: 51n * 10n ** 16n, // 0.51 USDC per XLM
184
+ expires: Math.floor(Date.now() / 1000) + 7 * 86_400
185
+ }]
186
+ })
187
+
188
+ // Cancel orders (an `update` with a zero amount under the hood)
189
+ await client.cancel('G...', [newOrderId])
190
+ ```
191
+
192
+ See [`src/index.d.ts`](src/index.d.ts) for the full typed API.
193
+
194
+ ### Methods
195
+
196
+ | Method | Description |
197
+ |---|---|
198
+ | `order(id)` | Fetch an order by id from on-chain storage. Returns `Promise<Order \| undefined>` (`undefined` for a missing or expired order). |
199
+ | `loadConfig()` | Fetch the contract configuration (contract `config`). Returns `Promise<Config>`. |
200
+ | `isFrozen()` | Whether the contract is frozen, trading and order management operations blocked (contract `frozen`). Returns `Promise<boolean>`. |
201
+ | `getMarket(selling, buying)` | Fetch the market record for an asset pair, either order (contract `market`). Returns `Promise<Market \| undefined>`. |
202
+ | `buy(params)` | Trade with the DEX and create a buy limit order if the quote is not fully executed (`params: BuyTradeArguments`). Returns `Promise<[sold, bought, newOrderId \| undefined]>`. |
203
+ | `sell(params)` | Trade with the DEX and create a sell limit order if the quote is not fully executed (`params: SellTradeArguments`). Returns `Promise<[sold, bought, newOrderId \| undefined]>`. |
204
+ | `estimateBuy(params)`, `estimateSell(params)` | Simulate `buy`/`sell` without signing or submitting, to show the network fee first. Returns `Promise<TradeEstimate>`: `fee` (maximum total, stroops), `inclusionFee`, `resourceFee` (including the rent of a new order), and the expected `sold`, `bought` and `orderId`. |
205
+ | `update(params)` | Change the amount, the price and the expiration of several orders in place or remove them (zero `amount`), and optionally set allowances; missing orders are skipped, expired ones are revived, and an updated order's entry lifetime is extended to cover its expiration +1 day (`params: UpdateArguments`). Approvals and removals work in a frozen contract; up to 90 orders per. Returns `Promise<bigint[]>` with the ids updated or removed. |
206
+ | `cancel(trader, ids)` | Cancel existing orders, expired ones included (`trader` is the owner address; `ids` is a `bigint[]`, non-existent orders are ignored). Client sugar: the contract has no `cancel`, this calls `update` with a zero amount per id; up to 90 orders per call. |
207
+ | `crossfill(trader, takerOrderId, orders)` | Fill an existing order against matching orders from the book; profits from price inefficiencies (the crossed spread) go to `trader`. Returns `Promise<[sold, bought, surplus]>`: the amount the taker order sold, the amount it received and the surplus paid to `trader`. |
208
+ | `swap(params)` | Swap tokens across several markets along a route (`params: SwapArguments`); the contract holds the intermediate hop proceeds only within the call. Returns `Promise<[sold, bought]>`. |
209
+ | `keepalive(days?)` | Extend the contract instance and code lifetime to `days` (30 by default, at most the network maximum)Days are converted into ledgers with the configured `Config.ledger_time` (5 seconds when it cannot be read). Anyone can send it, and it works while the contract is frozen. Other calls extend the contract only when less than 3 days are left. Returns `Promise<number>`, the ledger both entries live until. |
210
+ | `requote(selling, buying)` | Re-check both market assets against the price oracle and cache fresh prices for trading; the market record and the cache are rewritten only when they change. When the simulation writes nothing (the market and the cached prices are current, or the oracle has no newer price), no transaction is submitted and the simulated record is returned. Permissionless, blocked while frozen. Returns `Promise<Market \| undefined>` with the updated record (`undefined` for an unknown pair). |
211
+ | `subsidize(params)` | Extend the oracle price feeds access of a market, creating the market if it does not exist yet, by burning exactly `amount` XRF from the sponsor (`params: SubsidizeArguments`). Returns `Promise<bigint[]>` with the new expiration timestamps. |
212
+
213
+ Standalone helper: `orderId(owner, nonce)` (see below).
214
+
215
+ The safety admin entry points (`freeze`, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days`,
216
+ `set_ledger_time`) are skipped: they are operated outside the client.
217
+
218
+ The contract itself caps neither the fills of a trade nor the orders of an `update`, the limitations come from the
219
+ network's per-transaction limits. A trade settles at most 20 maker orders (`MAX_FILLS`). Each listed order the contract
220
+ skips adds a `skip` event, and every trade adds the transfer that forwards the makers' assets to the taker, so 20 fills
221
+ leave room for up to 3 skipped orders. An `update` fits about 100 changes or removals. These numbers follow the network
222
+ limits: when a protocol upgrade raises them, more fills and updates can fit in one transaction.
223
+
224
+ ### Markets and prices
225
+
226
+ A `Limit` trade needs an open market for its pair: without one it fails with `AssetsNotVerifiedByOracle` (`721`).
227
+ `Fill`/`FillOrKill` trades and `swap` only cross existing orders and need no market. A market is opened only by
228
+ `subsidize({sponsor, selling, buying, amount})` (either asset order opens the same market), which requires at least one
229
+ of the assets to be quoted by the price oracle:
230
+
231
+ - On a pair without a market, `amount` must cover `Config.market_listing_fee` (`InvalidAmount`, `706`, otherwise). The
232
+ fee is burned through an oracle `track` call, and whatever is left of `amount` through a second one (skipped when
233
+ nothing is left). The sponsor signs both `track` calls and their XRF `burn` sub-invocations and never burns more than
234
+ `amount`.
235
+ - On an existing market the whole `amount` extends the price feeds access of its quoted assets.
236
+ - `selling` and `buying` must differ (`InvalidMatch`, `704`).
237
+
238
+ The listing fee is derived: the contract computes it as `daily_fee × listing_min_days` from the oracle's daily fee, and
239
+ `loadConfig()` returns both values. `listing_min_days` is 90 at deployment, and the safety admin can set it from 0 to
240
+ 255 days. The fee pays one `track` call split across the listed assets, so at 90 days a pair with one listed asset gets
241
+ 90 days of feed and a pair with both listed 45 days each.
242
+
243
+ `buy`, `sell` and `update` never call the oracle. They value orders against the prices cached by `requote` and
244
+ `subsidize`, on the selling asset when it is listed and priced and otherwise on the buying asset; no usable price on
245
+ either listed asset (missing or older than 72 hours) fails with `AssetPriceOracleFetchFailed` (`722`). Keepers call
246
+ `requote(base, quote)` periodically for every active market (permissionless, moves no funds, blocked while frozen).
247
+ `update` cannot change an order of a market whose assets the oracle no longer quotes (`AssetsNotVerifiedByOracle`,
248
+ `721`), but removing it still works.
249
+
250
+ ### Order expiration
251
+
252
+ `buy`/`sell` take an optional `expires` UNIX timestamp in seconds (0 or omitted means no expiration). It applies to the
253
+ order created for the remainder of a `Limit` trade and must be in the future (`InvalidExpiration`, `707`); other kinds
254
+ ignore it. An expired order is invisible to `order()`, skipped by matching and treated as gone by `crossfill` (as the
255
+ taker), but it can still be cancelled (removed by `update`), and `update` revives it when given an `expires` of 0 or in
256
+ the future. Its id becomes free again, so a new order with the same nonce overwrites it. No event is emitted when an
257
+ order expires.
258
+
259
+ ### Allowances
260
+
261
+ The contract holds no user funds between calls. Every asset a trader sells through AXIS needs a standing allowance
262
+ granted to the contract on the token (`approve(from = trader, spender = AXIS, amount, liveUntil)`). Fills are settled
263
+ with `transfer_from`, the contract acting as the spender: each maker's asset goes to the contract, the taker pays each
264
+ maker directly, and the contract forwards what the makers delivered to the taker in one transfer at the end. Orders on
265
+ the book are backed by the owner's balance and allowance. Matching never removes, trims or limits an order.
266
+
267
+ A listed order whose maker's backing left does not cover the fill, whose maker cannot receive the taker's asset (a
268
+ missing or deauthorized trustline), or whose maker's asset cannot be collected is skipped and left unchanged, and a
269
+ `skip` event names it. The order owner is the party at fault. In a `crossfill` the skipped order can be the taker order,
270
+ whose owner cannot back it or be paid: the call then returns `[0n, 0n, 0n]`.
271
+
272
+ A payment to a maker that fails (the taker cannot pay, or the maker cannot be credited although authorized, e.g. a full
273
+ trustline) fails the whole call with the token's own error. The client throws it with `tokenError: true` and blames
274
+ neither side.
275
+
276
+ A taker who cannot receive the bought asset fails the call with `CannotReceive` (`708`). The contract cannot hold an
277
+ asset whose issuer requires authorization (`AUTH_REQUIRED`) until the issuer authorizes it: buying such an asset fails
278
+ with `IntermediaryCannotReceive` (`712`). Selling it needs no contract authorization. A `swap` is strict: any transfer
279
+ that fails fails the whole call.
280
+
281
+ Pass `approve: {amount, liveUntil}` to `buy`, `sell` or `swap` to grant (or reset) the allowance on the selling asset as
282
+ part of the same transaction (set `asset` to approve another token). `update` takes a separate
283
+ `approvals: [{asset, amount, liveUntil}]` list: each entry must name its asset, an asset without an entry keeps its
284
+ current allowance, and a zero amount revokes. The amount is absolute, not a delta, so the signed authorization does not
285
+ depend on ledger state; when several approvals name the same asset, the last one wins. `cancel` never moves tokens.
286
+
287
+ ### Order IDs and nonces
288
+
289
+ An order ID is chosen by the client through a `u64` nonce:
290
+
291
+ ```
292
+ id = u128::from_be_bytes(sha256(xdr(ScVec[owner: Address, nonce: u64]))[0..16])
293
+ ```
294
+
295
+ - `buy`/`sell` generate the nonce internally on every call (`Date.now() << 22 | 22 random bits`, fits `u64` until 2109);
296
+ callers never supply one. The id of the order created for the remainder is returned by the call.
297
+ - `orderId(owner, nonce)` computes the id locally for a known nonce. `buy`/`sell` use it to declare the new order entry
298
+ in the footprint before the transaction is signed (see below); custom pipelines that pick their own nonce can use it
299
+ the same way. The contract has no view for it.
300
+ - A nonce must be unique among the owner's live orders: the contract rejects a duplicate with `OrderExists` (`711`,
301
+ available as `error.code` on the thrown error). Retrying the call generates a fresh nonce.
302
+
303
+ ### Types
304
+
305
+ #### `OrderKind`
306
+
307
+ Trading order type — instructions to the contract on how to execute the trade.
308
+
309
+ | Value | Numeric | Description |
310
+ |---|---|---|
311
+ | `Limit` | `1` | Execute the trade, creating a limit order if not executed in full. |
312
+ | `Fill` | `2` | Execute the trade without creating a limit order. |
313
+ | `FillOrKill` | `3` | Execute the trade, fail if it cannot be executed in full. |
314
+
315
+ #### `TradeDirection`
316
+
317
+ Trade direction instructions.
318
+
319
+ | Value | Numeric | Description |
320
+ |---|---|---|
321
+ | `Sell` | `1` | Sell a fixed amount of asset. |
322
+ | `Buy` | `2` | Buy a fixed amount of asset. |
323
+
324
+ #### `ClientInitializationParams`
325
+
326
+ Parameters passed to the `AxisContractClient` constructor.
327
+
328
+ | Property | Type | Description |
329
+ |---|---|---|
330
+ | `publicKey` | `string` | Public key of the account that will interact with the contract. |
331
+ | `signTransaction` | `SignTransactionCallback` | Callback for signing transactions generated by the client. |
332
+ | `rpcUrl` | `string` | URL of the RPC server. |
333
+ | `contractId` | `string` | DEX contract id. |
334
+ | `networkPassphrase?` | `string` | Network passphrase (Pubnet passphrase by default). |
335
+ | `fee?` | `string` | Inclusion fee bid in stroops (`'100000'`, 0.01 XLM, by default). The resource fee from simulation is added on top. |
336
+ | `autoFootprint?` | `boolean` | 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). |
337
+
338
+ #### `SignTransactionCallback`
339
+
340
+ `(xdr: string, opts?: {networkPassphrase?, address?, submit?, submitUrl?}) => Promise<{signedTxXdr, signerAddress?, error?}>`
341
+
342
+ Callback for signing transactions generated by the client, in the `@stellar/stellar-sdk` 17 contract client shape. It
343
+ receives the transaction XDR and the network passphrase, and resolves to the signed transaction XDR. Stellar Wallets
344
+ Kit's
345
+ `signTransaction` matches it (pass the connected `address` along), and a `Keypair` signer is a few lines:
346
+ `TransactionBuilder.fromXDR(xdr, opts.networkPassphrase)`, `tx.sign(keypair)`, `{signedTxXdr: tx.toXDR()}`.
347
+
348
+ #### `Approval`
349
+
350
+ Token allowance granted to the contract as part of the call.
351
+
352
+ | Property | Type | Description |
353
+ |---|---|---|
354
+ | `asset?` | `string` | Token the allowance is granted on: defaults to `selling` for `buy`, `sell` and `swap`, required in `update` approvals. |
355
+ | `amount` | `bigint` | Absolute allowance amount (0 revokes the approval). |
356
+ | `liveUntil` | `number` | Ledger sequence the allowance lives until (at most ~180 days ahead). |
357
+
358
+ #### `TradeArguments`
359
+
360
+ Base arguments shared by `buy` and `sell`.
361
+
362
+ | Property | Type | Description |
363
+ |---|---|---|
364
+ | `kind` | `OrderKind` | Trading order behavior. |
365
+ | `trader` | `string` | Trader address. |
366
+ | `amount` | `bigint` | Tokens amount. |
367
+ | `selling` | `string` | Selling token address. |
368
+ | `buying` | `string` | Buying token address. |
369
+ | `price` | `bigint` | Price a trader is willing to accept (18 decimals). |
370
+ | `orders?` | `bigint[]` | List of order IDs to match before creating the order on-chain. |
371
+ | `expires?` | `bigint \| number` | Expiration UNIX timestamp (seconds) of the order created for a `Limit` remainder, 0 or omitted = none. |
372
+ | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
373
+
374
+ #### `SellTradeArguments`
375
+
376
+ Extends `TradeArguments` (passed to `sell`).
377
+
378
+ | Property | Type | Description |
379
+ |---|---|---|
380
+ | `amount` | `bigint` | Amount of `selling` tokens to sell. |
381
+ | `price` | `bigint` | Price a trader is willing to accept — minimum `buying` tokens per 1 `selling`. |
382
+
383
+ #### `BuyTradeArguments`
384
+
385
+ Extends `TradeArguments` (passed to `buy`).
386
+
387
+ | Property | Type | Description |
388
+ |---|---|---|
389
+ | `amount` | `bigint` | Amount of `buying` tokens to acquire. |
390
+ | `price` | `bigint` | Price a trader is willing to accept — maximum `selling` tokens per 1 `buying`. |
391
+
392
+ #### `TradeStep`
393
+
394
+ A trade step in a multi-market swap path.
395
+
396
+ | Property | Type | Description |
397
+ |---|---|---|
398
+ | `asset` | `string` | Asset to buy at this step. |
399
+ | `orders` | `bigint[]` | Maker order IDs to match. |
400
+
401
+ #### `SwapArguments`
402
+
403
+ Arguments passed to `swap`.
404
+
405
+ | Property | Type | Description |
406
+ |---|---|---|
407
+ | `direction` | `TradeDirection` | Trade direction: `Sell` or `Buy`. |
408
+ | `trader` | `string` | Trader address. |
409
+ | `selling` | `string` | Token address sent by the trader. |
410
+ | `sellingAmount` | `bigint` | Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`). |
411
+ | `buyingAmount` | `bigint` | Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`). |
412
+ | `path` | `TradeStep[]` | Ordered list of the trade route steps. |
413
+ | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
414
+
415
+ #### `UpdateArguments`
416
+
417
+ | Property | Type | Description |
418
+ |---|---|---|
419
+ | `trader` | `string` | Orders owner. |
420
+ | `updates` | `OrderUpdate[]` | New amount, price and expiration per order id. |
421
+ | `approvals?` | `Approval[]` | Allowances granted before the backing check, each naming its `asset`; an asset without an approval keeps its current allowance. |
422
+
423
+ #### `OrderUpdate`
424
+
425
+ | Property | Type | Description |
426
+ |---|---|---|
427
+ | `id` | `bigint` | Order id. |
428
+ | `amount` | `bigint` | New amount to sell, `0` removes the order. |
429
+ | `price` | `bigint` | New order price (ignored for a removal). |
430
+ | `expires?` | `bigint \| number` | New expiration UNIX timestamp (seconds), 0 or omitted = none. |
431
+
432
+ #### `SubsidizeArguments`
433
+
434
+ | Property | Type | Description |
435
+ |---|---|---|
436
+ | `sponsor` | `string` | Address paying for the oracle feeds (and the listing fee of a new market). |
437
+ | `selling` | `string` | First market asset. |
438
+ | `buying` | `string` | Second market asset (either order opens the same market). |
439
+ | `amount` | `bigint` | Amount of XRF fee tokens to burn; at least `Config.market_listing_fee` to open a market. |
440
+
441
+ #### `Order`
442
+
443
+ Order properties, stored on-chain (returned by `order()` call).
444
+
445
+ | Property | Type | Description |
446
+ |---|---|---|
447
+ | `id` | `bigint` | Order ID, derived from the owner and the client nonce. |
448
+ | `owner` | `string` | Owner of the order. |
449
+ | `selling` | `string` | Selling token address. |
450
+ | `buying` | `string` | Buying token address. |
451
+ | `amount` | `bigint` | Amount left to sell. |
452
+ | `price` | `bigint` | Order price (`buying` per 1 `selling`, 18 decimals). |
453
+ | `expires` | `bigint` | Expiration UNIX timestamp in seconds (0 = no expiration). |
454
+
455
+ #### `Config`, `Market`, `MarketSide`
456
+
457
+ Decoded straight from the contract, so field names keep the contract's snake_case:
458
+ `Config {safety_admin, oracle, listing_min_days, market_listing_fee, min_trade_size, ledger_time}`,
459
+ `Market {base, quote, created}` (the assets in canonical order, `created` in UNIX seconds),
460
+ `MarketSide {asset, listed, decimals}`. `market_listing_fee` is derived from the oracle
461
+ (`daily_fee × listing_min_days`), never supplied. The contract is deployed with
462
+ `__constructor(safety_admin, oracle, min_trade_size)`, which sets
463
+ `listing_min_days` to 90 and `ledger_time` (the ledger close time lifetimes are converted with) to 5 seconds. An asset
464
+ whose token and oracle decimals add up to more than 37 is recorded as unlisted.
465
+
466
+ ### Contract events
467
+
468
+ Trading events use the `vec` data format: the event data is a vector of the fields in the order listed. There is no
469
+ trade or swap id; indexers derive one from the ledger, transaction and event position.
470
+
471
+ | Event | Topics | Data | Notes |
472
+ |---|---|---|---|
473
+ | `trade` | `trade, selling, buying` (assets sold and bought by the taker) | `order, taker, maker, sold, bought, left` | One per fill. `left` is the order amount after the fill, `0` when the order was filled in full (or what is left became dust) and removed. Fills emit no order event. `taker` is the account the fill is made for, never the contract: the trader on every `swap` hop, and the caller on every `crossfill` fill, the maker fills (paid by the taker order owner) and a last event reporting the taker order fill with the owner as the maker alike. Summed per account, the `trade` events of a call give each account's net token movement. |
474
+ | `swap` | `swap, selling, buying` | `trader, sold, bought` | One per `swap` call, after the fills of every hop. |
475
+ | `new` | `new, selling, buying` | `id, owner, price, amount, expires` | An order created. `id` is a `u128`, `expires` a `u64` (0 = none). |
476
+ | `mod` | `mod` | `id, price, amount, expires` | An order changed outside a fill: `update` (new price, amount and expiration) or removal by `update`/`cancel` (`amount = 0`). Nothing is emitted when an order expires. |
477
+ | `skip` | `skip` | `order: u128` | A listed order its maker could not settle (backing short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected). The order is left unchanged. Also a `crossfill` taker order its owner cannot back or be paid for. |
478
+ | `refresh` | `refresh, base, quote` (market assets in canonical order) | none | Every check of a market against the oracle (`requote`, `subsidize`, market creation). |
479
+ | `freeze` | `freeze` | `frozen: bool` | |
480
+ | `config` | `config` | `Config` | The configuration after the constructor, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days` or `set_ledger_time`. |
481
+
482
+ Typed as `TradeContractEvent`, `SwapContractEvent`, `OrderCreatedContractEvent`, `OrderUpdatedContractEvent`,
483
+ `OrderSkippedContractEvent`, `MarketRefreshContractEvent`, `FreezeContractEvent`, `ConfigChangedContractEvent` in
484
+ [`src/index.d.ts`](src/index.d.ts).
485
+
486
+ ### Contract errors
487
+
488
+ Simulation failures caused by the contract are thrown as `Error` with `message` `Contract execution error: #<code>
489
+ <name>` and a numeric `code` property. A failure raised by a token the call invoked (a settlement transfer) is thrown as
490
+ an `Error` with the token's `code`, `tokenError: true` and the token `contract`, named after `TokenErrors` (for example
491
+ `#10 BalanceError`, which a payer without the balance and a recipient at its trustline limit both raise). Other
492
+ simulation failures are rethrown as the raw RPC error string, not an `Error`.
493
+
494
+ The client signs with the wallet callback (wallet errors pass through as the SDK throws them), then sends the
495
+ transaction over RPC and waits for its result. A submitted transaction that does not go through throws an `Error` with
496
+ the transaction `hash` and a `status`:
497
+
498
+ | `status` | Meaning | Other properties |
499
+ |---|---|---|
500
+ | `ERROR` | The network rejected it, nothing was charged. | `result`: the result code, Horizon style, for example `tx_bad_seq` (another transaction of the account went through first) or `tx_insufficient_fee`. A transaction the RPC server accepted but the network dropped because another transaction of the account used its sequence number is reported the same way. |
501
+ | `TRY_AGAIN_LATER` | Not accepted for now: the network is congested, or another transaction of the account is pending. | |
502
+ | `FAILED` | Applied and failed on-chain, the fee was charged. | `result` (`tx_failed`), `opResult` (for example `invoke_host_function_trapped`), and `code` (plus `tokenError` and `contract`) when the RPC server returns the diagnostic events of the transaction: a call that passed simulation can still fail when the book changes before it applies, for example `709` for a `FillOrKill` trade or a `swap`. |
503
+ | `TIMEOUT` | Not seen before its time bounds expired, it can no longer be included. | |
504
+
505
+ When the RPC server cannot be reached at submission, the client looks the transaction up for a few seconds before
506
+ rethrowing the request error with the transaction `hash`. `ContractErrors` maps the contract codes:
507
+
508
+ | Code | Name | Meaning |
509
+ |---|---|---|
510
+ | 701 | `NotAuthorized` | An `update` or `cancel` lists an order that `trader` does not own. |
511
+ | 702 | `InsufficientBalance` | The order is not backed by the trader's balance. |
512
+ | 703 | `InsufficientAllowance` | The allowance granted to the contract does not cover the order. |
513
+ | 704 | `InvalidMatch` | `selling` equals `buying` (trades and `subsidize`), or a `swap` has no path or a non-positive amount (a listed order of another pair is skipped, not an error). |
514
+ | 705 | `InvalidPrice` | Price outside `[1, 10^36]`. |
515
+ | 706 | `InvalidAmount` | An amount is not positive, a `subsidize` that opens a market is below the listing fee, or a configuration value is out of range. |
516
+ | 707 | `InvalidExpiration` | An `expires` is neither 0 nor in the future. |
517
+ | 708 | `CannotReceive` | The trader cannot receive the bought asset: a missing or deauthorized trustline, or a full one (the transfer forwarding the makers' assets failed). Never a maker's fault. |
518
+ | 709 | `NotFilled` | A `FillOrKill` trade or `swap` cannot be executed in full. |
519
+ | 710 | `OrderNotFound` | The order does not exist or has expired. |
520
+ | 711 | `OrderExists` | A live order with the same id exists (retry the call). |
521
+ | 712 | `IntermediaryCannotReceive` | The contract cannot hold an asset it passes on: the asset requires issuer authorization and the issuer has not authorized the AXIS contract yet. |
522
+ | 720 | `OrderSizeTooSmall` | Order value below the minimum order size, or the remainder is dust. |
523
+ | 721 | `AssetsNotVerifiedByOracle` | The pair has no market (open it with `subsidize`), or neither asset is listed on the price oracle (a `Limit` trade, an `update` that changes an order, `subsidize`). |
524
+ | 722 | `AssetPriceOracleFetchFailed` | No listed market asset has a usable cached price (none cached within the last 72 hours). |
525
+ | 723 | `InvalidOracleConfig` | The price oracle does not satisfy the contract requirements (at most 24 decimals, a daily fee). |
526
+ | 730 | `Frozen` | Trading is blocked (order removals and approvals still work). |
527
+ | 740 | `Overflow` | An arithmetic invariant was violated. Other arithmetic overflows trap as a host error. |
528
+
529
+ ## AxisApiClient
530
+
531
+ HTTP client for the AXIS REST API. Uses the standard `fetch` API - no extra dependencies.
532
+
533
+ ```js
534
+ import {AxisApiClient, AxisApiError} from '@axis-markets/client'
535
+
536
+ const api = new AxisApiClient('https://demo-api.axis.markets') // testnet
537
+ const USDC = 'USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' // testnet USDC
538
+
539
+ // Quote: sell a fixed amount of the source asset (strict send)
540
+ const sellQuote = await api.quoteSell({
541
+ sellingAsset: 'XLM',
542
+ buyingAsset: USDC,
543
+ amount: '10000000' // stroops (1 unit = 10,000,000 stroops)
544
+ })
545
+ if (sellQuote.status !== 'success') {
546
+ console.log(sellQuote.error) // 'unfeasible' (not enough liquidity) or 'rejected' (contract frozen, or an asset the contract cannot hold)
547
+ }
548
+
549
+ // Quote: buy a fixed amount of the destination asset (strict receive)
550
+ const buyQuote = await api.quoteBuy({
551
+ sellingAsset: 'XLM',
552
+ buyingAsset: USDC,
553
+ amount: '5000000'
554
+ })
555
+
556
+ // Order book depth around the mid price
557
+ const depth = await api.getDepth({market: `XLM/${USDC}`, depth: 20})
558
+
559
+ // OHLCVT candles of the last week
560
+ const candles = await api.getCandles({
561
+ market: `XLM/${USDC}`,
562
+ from: Math.floor(Date.now() / 1000) - 7 * 86_400, // UNIX seconds, the window starts at 0 (1970) without it
563
+ resolution: '1h',
564
+ order: 'asc'
565
+ })
566
+
567
+ // 24h ticker for every market
568
+ const {ticker} = await api.getTicker24h()
569
+ ```
570
+
571
+ ### AxisApiClient Methods
572
+
573
+ | Method | Description |
574
+ |---|---|
575
+ | `quoteSell({sellingAsset, buyingAsset, amount, direct?, maxPrice?})` | Best trade routes for selling a fixed amount of the source asset (strict send). Each hop lists the order ids to pass to the contract (the orders the quote fills, followed on a direct route by spare orders used only when the contract passes over one of them, at most 19 in all) and `worstPrice`, the highest price among the filled orders (spares are priced at or below it, or within `maxPrice`). Without enough liquidity it resolves with `status: 'unfeasible'` and an `error`, and while the contract is frozen with `status: 'rejected'`. It throws `AxisApiError` with status 409 when the server is not ready or routing fails, and 400 for invalid parameters. With `direct` and `maxPrice` (the highest maker price to cross, in `worstPrice` units) it quotes the crossing of a limit order: orders priced above the limit are left out and the route may trade less than `amount`. |
576
+ | `quoteBuy({sellingAsset, buyingAsset, amount, direct?, maxPrice?})` | Best trade routes for buying a fixed amount of the destination asset (strict receive). Resolves and throws like `quoteSell`. |
577
+ | `getDepth({market, depth?, step?, limit?})` | Order book depth around the mid price (`depth` is the ± band %, 0–100, default 20) in price levels on multiples of `step` (e.g. `"0.0005"`; 5 significant digits by default), `limit` levels per side (default 100). Bids are rounded down and asks up, so a level price crosses every order in it; `bestBid`/`bestAsk` are the exact best prices. |
578
+ | `getCandles({market, from?, to?, resolution?, order?})` | OHLCVT candlestick data. `resolution` accepts seconds or an alias (`5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `12h`, `1d`, `3d`, `1w`, `2w`; default `auto`). |
579
+ | `getTicker24h()` | 24-hour ticker statistics for every available market. |
580
+ | `getMarkets({cursor?, limit?})` | Pairs with orders on the book, with pagination (cached for up to 30 minutes). Markets opened on-chain come from `getContract()`. |
581
+ | `getContract()` | Contract state tracked by the indexer: contract `address`, `frozen`, `config` (`safetyAdmin`, `oracle`, `listingMinDays`, `marketListingFee`, `minTradeSize`, `ledgerTime`) and active `markets` (`base`, `quote`, `created`, `refreshed`). |
582
+ | `getOrders({owner?, asset?, cursor?, limit?})` | Active orders, filterable by owner or asset (`asset` may be a string or string array). |
583
+ | `getOrder(id)` | A single active order by ID (throws `AxisApiError` with status 404 if not found). |
584
+ | `getAccount(address)` | Every live order of an account (not paginated) and its backing per traded token. |
585
+ | `getOrderHistory({owner?, pair?, cursor?, limit?})` | Archived/historical orders, newest first (`pair` = `[base, quote]` contract ids). |
586
+ | `getTrades({trader?, pair?, cursor?, limit?})` | Recent trades and swaps, newest first (`type: 'trade' \| 'swap'`, `pair` = `[base, quote]` contract ids). The fill of a `crossfill` taker order carries `crossfill: true`: its `taker` is the caller paid the surplus, and the aggregator leaves it out of candles and volume. |
587
+ | `getFailures({account?, fn?, cursor?, limit?})` | Failed AXIS calls, newest first (diagnostics only): calls made by the transaction or through another contract, in failed transactions or caught by a calling contract (`caught`). `account` matches the caller and both parties of a failed transfer. Each record has a `reason` (`contract`, `transfer`, `resources`, `auth`, `unknown`), the contract `error` and the failed `transfer`. A record never blames a party: a failed transfer names both sides. |
588
+
589
+ Classic asset strings (`XLM`, `CODE:Issuer`, `CODE-Issuer`) are accepted by `quoteSell`, `quoteBuy`, `getDepth` and
590
+ `getCandles`, next to Soroban contract ids. The `asset`, `pair` and `owner` filters of the order and trade lists need
591
+ contract ids and account addresses. Markets use the `BASE/QUOTE` convention, each side in any of these formats. Amounts
592
+ are expressed in stroops on input and returned as strings. Orders, trades and quotes carry raw integer amounts and
593
+ 18-decimal contract prices, while `getDepth`, `getCandles` and `getTicker24h` return decimal prices and whole-unit
594
+ volumes. Order ids are decimal strings of the `u128` id. They are not sequential, so pagination passes the `cursor`
595
+ field of the last received row (the creation position of an order, the id of a trade), not the id. Orders carry `backed`
596
+ (the amount the maker can actually deliver) and `backing` when the indexer tracks maker balances and allowances. Account
597
+ backing records also carry `headroom` in the assets the account receives: the room left under its trustline limit
598
+ (omitted when unlimited or unknown).
599
+
600
+ ### Error handling
601
+
602
+ Non-success responses throw an `AxisApiError` carrying the HTTP `status` code:
603
+
604
+ ```js
605
+ try {
606
+ await api.getOrder('123')
607
+ } catch (e) {
608
+ if (e instanceof AxisApiError && e.status === 404) {
609
+ // not found
610
+ }
611
+ throw e
612
+ }
613
+ ```
614
+
615
+ ## Order footprint
616
+
617
+ Soroban RPC simulation records only the ledger entries the contract actually touched against the state at simulation
618
+ time. The orderbook matching loop stops as soon as the taker is filled, and orders it skipped are recorded read-only
619
+ without their makers' entries. If the book moves before the transaction lands - an order is partly filled, repriced back
620
+ into range, its maker restores the backing, an earlier order shrinks, or an expired order is revived - the contract has
621
+ to read and write entries that are missing from the footprint, resulting in a rejection. Likewise, a `Limit` trade that
622
+ simulation filled in full may create an order for a remainder at apply time under an entry the simulation never saw.
623
+
624
+ To make trading transactions resilient to such changes, `buy`, `sell`, `crossfill` and `swap` patch the simulated
625
+ transaction before signing. Every order id passed in `orders` (plus the taker order id for `crossfill`, every path step
626
+ for `swap`, and the remainder id `orderId(trader, nonce)` for `Limit` trades) is declared in the read-write footprint,
627
+ and so are the entries the settlement of the call writes whatever makers fill: the contract's own balance of every asset
628
+ passing through it (the bought asset, every hop asset of a `swap`, the asset a `crossfill` taker order buys) and the
629
+ receiver's balance of the bought asset. Then every entry the settlement may write for the maker behind each listed
630
+ order: the balance of the asset the maker sells, the maker's allowance on it to the contract, and the balance of the
631
+ asset the maker receives (an account entry for XLM, a trustline for a classic asset, the token's `Balance` entry for a
632
+ contract address, none for the asset issuer). The client loads the listed orders and the token instances with one RPC
633
+ `getLedgerEntries` call (the classic asset behind each token is cached per client) and adds entries in that order while
634
+ the footprint limits (200 read-write, 400 total) allow. Tokens that are not Stellar Asset Contracts keep what the
635
+ simulation recorded: their storage layout is unknown. The declared instructions, write bytes and resource fee grow with
636
+ every added entry, and the disk read bytes with every added account or trustline entry the simulation did not read; the
637
+ surplus resource fee is refundable, but every declared read-write entry pays the write-entry fee, so routers should list
638
+ only orders they expect to fill. `update` declares the updated order ids only. Pass `autoFootprint: false` to the
639
+ constructor to opt out.
640
+
641
+ Order entries are keyed by the raw `u128` order id in persistent contract storage and hold a positional vector
642
+ `[owner, selling, buying, amount, price, expires?]`. The helpers exported for custom pipelines:
643
+
644
+ ```js
645
+ import {orderId} from '@axis-markets/client'
646
+ import {collectOrderIds, completeFootprint} from '@axis-markets/client/footprint'
647
+ import {rpc} from '@stellar/stellar-sdk'
648
+
649
+ // the raw `trade` entry point takes the nonce explicitly - any u64 unique among the owner's live orders
650
+ const nonce = (BigInt(Date.now()) << 22n) | BigInt(crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff)
651
+ const tx = await client.client.trade({...payload, nonce, expires: 0n}, {fee})
652
+ await completeFootprint(tx, contractId, collectOrderIds(payload.orders, [orderId(payload.trader, nonce)]), {
653
+ server: new rpc.Server(rpcUrl),
654
+ tokens: [payload.selling, payload.buying],
655
+ passThrough: [payload.buying], // makers deliver to the contract
656
+ receiver: payload.trader, // which forwards to the trader
657
+ bought: payload.buying
658
+ })
659
+ await tx.signAndSend()
660
+ ```
661
+
662
+ `ensureOrdersFootprint(tx, contractId, orderIds)` declares the order entries alone (no RPC call), and
663
+ `orderLedgerKey`, `balanceLedgerKey`, `allowanceLedgerKey`, `instanceLedgerKey`, `decodeStoredOrder` and
664
+ `decodeSacAsset` build and decode the individual entries.
665
+
666
+ ## Development
667
+
668
+ Run tests:
669
+
670
+ ```
671
+ pnpm test
672
+ ```
673
+
674
+ Bundling script:
675
+
676
+ ```
677
+ pnpm run prepare
678
+ ```
679
+
680
+ Bundles the ESM source (`src/`) into a UMD library (`lib/`) via webpack. Type definitions located in `src/index.d.ts`.
681
+
682
+ ## License
683
+
684
+ MIT