@axis-markets/client 0.5.0 → 0.8.0

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