@axis-markets/client 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,10 +2,14 @@
2
2
 
3
3
  JavaScript SDK for [AXIS](https://axis.markets) Stellar DEX.
4
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 Aggregator WebSocket push API, with trading calls that
7
+ look up the crossing orders and manage allowances automatically.
5
8
  - **`AxisContractClient`** — wraps the on-chain AXIS smart contract for order management and trading (sign & send
6
- transactions, read orders).
9
+ transactions, read orders, markets and configuration).
7
10
  - **`AxisApiClient`** — a dependency-free HTTP client for the AXIS Aggregator and Indexer REST API (quotes, orderbook
8
11
  depth, candles, ticker, market/order/trade data).
12
+ - **`AxisStreamClient`** — WebSocket client of the Aggregator push API.
9
13
 
10
14
  ## Installation
11
15
 
@@ -13,7 +17,102 @@ JavaScript SDK for [AXIS](https://axis.markets) Stellar DEX.
13
17
  npm i @axis-markets/client
14
18
  ```
15
19
 
16
- Requires Node.js 20+ (or any modern browser).
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 Aggregator push
26
+ API, 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 Aggregator's
29
+ data source streams updates for that state to maintain consistent up-to-date state in memory.
30
+
31
+ ```js
32
+ import {Axis, TradeDirection} from '@axis-markets/client'
33
+
34
+ const axis = new Axis({
35
+ apiUrl: 'https://aggregator.axis.markets',
36
+ rpcUrl: 'https://soroban-testnet.stellar.org',
37
+ contractId: 'CBJ747MKAGQO2LMJPOTCOONAWBLIIBSLOQE325R457TE5MIS6RTDJ4DC',
38
+ networkPassphrase: 'Test SDF Network ; September 2015'
39
+ })
40
+ await axis.connect()
41
+ axis.on('frozen', frozen => console.log('trading', frozen ? 'suspended' : 'resumed'))
42
+
43
+ const market = axis.getMarket(XLM, USDC) // either order: market.a / market.b are in the contract order
44
+
45
+ const account = axis.account(publicKey, {signTransaction})
46
+ await account.ready
47
+ account.on('fill', ({order, sold, bought}) => console.log(`order ${order.id}: sold ${sold}, got ${bought}`))
48
+ account.on('filled', ({order}) => console.log(`order ${order.id} filled`))
49
+ account.on('expire', order => console.log(`order ${order.id} expired`))
50
+ account.on('backing', ({asset}) => console.log(asset, 'balance', account.getBalance(asset)))
51
+
52
+ // limit sell of 100 XLM at 0.25 USDC; crossing orders and the approval are handled by the account
53
+ const {sold, bought, orderId} = await account.sell({
54
+ selling: XLM,
55
+ buying: USDC,
56
+ amount: 1_000_000_000n,
57
+ price: 25n * 10n ** 16n
58
+ })
59
+ // market buy of 10 XLM (no price: crosses the book at the worst quoted maker price)
60
+ await account.buy({selling: USDC, buying: XLM, amount: 100_000_000n})
61
+ await account.update([{id: orderId, amount: 500_000_000n}])
62
+ await account.cancelAll({market})
63
+ await account.swap({selling: USDC, buying: EURC, amount: 10_000_000n, direction: TradeDirection.Sell, slippage: 0.005})
64
+ ```
65
+
66
+ **Allowances.** The contract holds no funds: an order is fillable up to `min(balance, allowance)` in the sold token, and
67
+ one allowance record backs every order selling it. Before each `sell`, `buy`, `swap` and a growing `update`, the account
68
+ checks the allowance and attaches to cover all active orders. A fill lowers the allowance and the order it fills in the
69
+ same pushed ledger, so the memory state stays consistent. The allowance is read over RPC only when the push connection
70
+ is down, the token is not tracked, or for 30 s after this client spent the token as a taker (the push reporting the
71
+ spend may lag behind). An order this client created counts as committed right away (`pending: true`) until the indexer
72
+ reports it.
73
+
74
+ **Balances.** While an account is subscribed, the Aggregator tracks it in every market token.
75
+ `account.balances` / `getBalance(asset)` give the spendable amount, and each change emits
76
+ `backing` event.
77
+
78
+ **Backing.** Each `AccountOrder` carries `backed` (its share of the budget, split by the indexer among the orders
79
+ selling the token oldest first), `backedPct` and `backingPending`.
80
+ `account.getAllowance(asset)` reports `balance`, `allowance`, `liveUntil`, `available` and `committed`.
81
+
82
+ | `Axis` | Description |
83
+ |---|---|
84
+ | `connect()` | Load the contract state and follow its changes. |
85
+ | `ledger`, `getLedger()` | Last ledger pushed by the Aggregator; current ledger (pushed, or RPC when stale). |
86
+ | `frozen`, `config`, `markets`, `loaded` | Contract state; `markets` is a `Map` of `AxisMarket` by canonical key. |
87
+ | `getMarket(x, y)` | Market of the asset pair in either order, `undefined` if not open. |
88
+ | `getOrder(id)` | Live order from a tracked account's memory or the Aggregator, `undefined` if gone. |
89
+ | `account(address, {signTransaction})` | `AxisAccount` of the trader (one per address). |
90
+ | `subscribeTicker(cb)` | 24h ticker of every market (canonical orientation); also fills `market.ticker`. |
91
+ | `keepalive(signer?)` | Extend the contract instance and code lifetime. |
92
+ | `close()` | Stop following the contract and every account. |
93
+ | events | `change`, `frozen`, `config`, `market` (`{market, created}`), `connection`, `ledger` |
94
+
95
+ | `AxisMarket` | Description |
96
+ |---|---|
97
+ | `a`, `b`, `key`, `base`, `quote`, `created`, `refreshed` | Canonical assets (`base` = `a`) and oracle check times. |
98
+ | `requote(signer?)` | Re-check the market against the oracle and cache prices (submits nothing when nothing changed). |
99
+ | `subsidize({amount, sponsor?, signer?})` | Extend the oracle feeds access of the market. |
100
+ | `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. |
101
+ | `subscribeTrades(cb)` | Recent trades, then each new fill. |
102
+ | `subscribeCandles({base?, resolution, limit?}, cb)` | Latest candles in the requested orientation (`limit`, default and max 200), then each candle changed by new trades. |
103
+
104
+ | `AxisAccount` | Description |
105
+ |---|---|
106
+ | `orders`, `backing`, `ready`, `loaded` | Open orders by id and backing by token, in memory. |
107
+ | `balances`, `getBalance(asset)`, `funded` | Spendable balances by token (every market token), whether the account exists. |
108
+ | `getOrders({market?, selling?, buying?})` | Open orders, newest first, including `pending` ones this client created. |
109
+ | `getOrder(id)`, `committed(asset)`, `getAllowance(asset)` | Order lookup, open amount selling a token, allowance summary. |
110
+ | `sell(params)`, `buy(params)` | Trade (`{selling, buying, amount, price?, kind?, expires?, orders?, approve?}`); without `price` it is a market order. Returns `{sold, bought, orderId?, order?, approve?}`. |
111
+ | `update(updates)` | Change orders (omitted fields keep their values). |
112
+ | `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of 100). |
113
+ | `crossfill(takerOrderId, orders?)` | Fill an open order against the book. |
114
+ | `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best Aggregator route. |
115
+ | events | `ready`, `new`, `pending`, `fill`, `filled`, `update`, `cancel`, `expire`, `remove`, `order`, `backing`, `approve`, `trade`, `swap`, `change`, `error` |
17
116
 
18
117
  ## AxisContractClient
19
118
 
@@ -29,13 +128,8 @@ const client = new AxisContractClient({
29
128
  signTransaction: async (xdr, context) => ({signedTxXdr: await wallet.sign(xdr)}) // tx sign callback
30
129
  })
31
130
 
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)
131
+ // Place a sell limit order (the remainder becomes a limit order if not fully executed).
132
+ // The id of the created order, if any, is returned as the third tuple element.
39
133
  const [sold, bought, newOrderId] = await client.sell({
40
134
  kind: OrderKind.Limit,
41
135
  trader: 'G...',
@@ -43,27 +137,118 @@ const [sold, bought, newOrderId] = await client.sell({
43
137
  selling: 'C...selling',
44
138
  buying: 'C...buying',
45
139
  price: 5_000_000n,
46
- orders: []
140
+ orders: [], // maker order ids to cross first (from the aggregator quote)
141
+ expires: Math.floor(Date.now() / 1000) + 86_400, // optional expiration of the created order (UNIX seconds)
142
+ approve: {amount: 1_000_000_0000n, liveUntil: 60_000_000} // optional in-call allowance on `selling`
143
+ })
144
+
145
+ // Fetch an order by id
146
+ const order = await client.order(newOrderId)
147
+
148
+ // Re-price an order in place (and keep it for another week)
149
+ await client.update({
150
+ trader: 'G...',
151
+ updates: [{
152
+ id: newOrderId,
153
+ amount: 500_0000n,
154
+ price: 5_100_000n,
155
+ expires: Math.floor(Date.now() / 1000) + 7 * 86_400
156
+ }]
47
157
  })
48
158
 
49
- // Cancel orders
50
- await client.cancel([lastId], 'G...')
159
+ // Cancel orders (an `update` with a zero amount under the hood)
160
+ await client.cancel('G...', [newOrderId])
51
161
  ```
52
162
 
53
- See [`src/index.d.ts`](src/index.d.ts) for the full typed API (`buy`, `sell`, `swap`, `fill_order`, `cancel`, `order`,
54
- `last`).
163
+ See [`src/index.d.ts`](src/index.d.ts) for the full typed API.
55
164
 
56
165
  ### Methods
57
166
 
58
167
  | Method | Description |
59
168
  |---|---|
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]>`. |
169
+ | `order(id)` | Fetch an order by id from on-chain storage. Returns `Promise<Order \| undefined>` (`undefined` for a missing or expired order). |
170
+ | `loadConfig()` | Fetch the contract configuration (contract `config`). Returns `Promise<Config>`. |
171
+ | `isFrozen()` | Whether the contract is frozen, trading and order management operations blocked (contract `frozen`). Returns `Promise<boolean>`. |
172
+ | `getMarket(selling, buying)` | Fetch the market record for an asset pair, either order (contract `market`). Returns `Promise<Market \| undefined>`. |
173
+ | `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]>`. |
174
+ | `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]>`. |
175
+ | `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. |
176
+ | `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>`. |
177
+ | `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`. |
178
+ | `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]>`. |
179
+ | `keepalive()` | Extend the contract instance and code lifetime to 180 days. Permissionless, works while frozen; keepers call it regularly (other calls extend the contract only when less than 3 days are left). Returns `Promise<void>`. |
180
+ | `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). |
181
+ | `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. |
182
+
183
+ Standalone helper: `orderId(owner, nonce)` (see below).
184
+
185
+ The safety admin entry points (`freeze`, `delegate`, `set_oracle`, `set_floor`) are not wrapped: they are operated
186
+ outside the client.
187
+
188
+ `cancel` and `update` process up to 100 orders per transaction; a trade matches at most 20 maker orders (`MAX_FILLS`),
189
+ and each listed order the contract skips adds a `skip` event, so 20 fills leave room for 6 skipped orders.
190
+
191
+ ### Markets and prices
192
+
193
+ A `Limit` trade needs an open market for its pair: without one it fails with `AssetsNotVerifiedByOracle` (`721`).
194
+ `Fill`/`FillOrKill` trades and `swap` only cross existing orders and need no market. A market is opened only by
195
+ `subsidize({sponsor, selling, buying, amount})` (either asset order opens the same market), which requires at least one
196
+ of the assets to be quoted by the price oracle:
197
+
198
+ - On a pair without a market, `amount` must cover `Config.market_listing_fee` (`InvalidAmount`, `706`, otherwise). The
199
+ fee is burned through an oracle `track` call, and whatever is left of `amount` through a second one (skipped when
200
+ nothing is left). The sponsor signs both `track` calls and their XRF `burn` sub-invocations and never burns more than
201
+ `amount`.
202
+ - On an existing market the whole `amount` extends the price feeds access of its quoted assets.
203
+
204
+ The listing fee is not configured: the contract derives it from the oracle's daily fee as `daily_fee × 90` whenever the
205
+ oracle is set, and `loadConfig()` returns it. The fee pays one `track` call split across the listed assets, so a pair
206
+ with one listed asset gets 90 days of feed and a pair with both listed 45 days each.
207
+
208
+ `buy`, `sell` and `update` never call the oracle. They value orders against the prices cached by `requote` and
209
+ `subsidize`, on the selling asset when it is listed and priced and otherwise on the buying asset; no usable price on
210
+ either listed asset (missing or older than 72 hours) fails with `AssetPriceOracleFetchFailed` (`722`). Keepers call
211
+ `requote(a, b)` periodically for every active market (permissionless, moves no funds, blocked while frozen).
212
+
213
+ ### Order expiration
214
+
215
+ `buy`/`sell` take an optional `expires` UNIX timestamp in seconds (0 or omitted means no expiration). It applies to the
216
+ order created for the remainder of a `Limit` trade and must be in the future (`InvalidExpiration`, `707`); other kinds
217
+ ignore it. An expired order is invisible to `order()`, skipped by matching and treated as gone by `crossfill` (as the
218
+ taker), but it can still be cancelled (removed by `update`), and `update` revives it when given an `expires` of 0 or in
219
+ the future. Its id becomes free again, so a new order with the same nonce overwrites it. No event is emitted when an
220
+ order expires.
221
+
222
+ ### Allowances
223
+
224
+ The contract holds no user funds. Every asset a trader sells through AXIS needs a standing allowance granted to the
225
+ contract on the token (`approve(from = trader, spender = AXIS, amount, liveUntil)`), and fills are settled with
226
+ `transfer_from` between maker and taker. Orders on the book are backed by the owner's balance and allowance. A listed
227
+ order fills only when its maker's backing left covers the fill and the maker can receive the taker's asset; otherwise,
228
+ or when the maker's transfer fails, it is skipped and left unchanged, and a `skip` event names it. Matching never
229
+ removes, trims or caps an order.
230
+
231
+ Pass `approve: {amount, liveUntil}` to `buy`, `sell` or `swap` to grant (or reset) the allowance on the selling asset as
232
+ part of the same transaction (set `asset` to approve another token). `update` takes a separate
233
+ `approvals: [{asset, amount, liveUntil}]` list: each entry must name its asset, an asset without an entry keeps its
234
+ current allowance, and a zero amount revokes. The amount is absolute, not a delta, so the signed authorization does not
235
+ depend on ledger state; when several approvals name the same asset, the last one wins. `cancel` never moves tokens.
236
+
237
+ ### Order ids and nonces
238
+
239
+ An order id is chosen by the client through a `u64` nonce:
240
+
241
+ ```
242
+ id = u128::from_be_bytes(sha256(xdr(ScVec[owner: Address, nonce: u64]))[0..16])
243
+ ```
244
+
245
+ - `buy`/`sell` generate the nonce internally on every call (`Date.now() << 22 | 22 random bits`, fits `u64` until 2109);
246
+ callers never supply one. The id of the order created for the remainder is returned by the call.
247
+ - `orderId(owner, nonce)` computes the id locally for a known nonce. `buy`/`sell` use it to declare the new order entry
248
+ in the footprint before the transaction is signed (see below); custom pipelines that pick their own nonce can use it
249
+ the same way. The contract has no view for it.
250
+ - A nonce must be unique among the owner's live orders: the contract rejects a duplicate with `OrderExists` (`711`,
251
+ available as `error.code` on the thrown error). Retrying the call generates a fresh nonce.
67
252
 
68
253
  ### Types
69
254
 
@@ -75,7 +260,7 @@ Trading order type — instructions to the contract on how to execute the trade.
75
260
  |---|---|---|
76
261
  | `Limit` | `1` | Execute the trade, creating a limit order if not executed in full. |
77
262
  | `Fill` | `2` | Execute the trade without creating a limit order. |
78
- | `FillOrKill` | `3` | Execute the trade, cancel if it was not executed in full. |
263
+ | `FillOrKill` | `3` | Execute the trade, fail if it cannot be executed in full. |
79
264
 
80
265
  #### `TradeDirection`
81
266
 
@@ -83,8 +268,8 @@ Trade direction instructions.
83
268
 
84
269
  | Value | Numeric | Description |
85
270
  |---|---|---|
86
- | `Sell` | `1` | Sell the base asset. |
87
- | `Buy` | `2` | Buy the base asset. |
271
+ | `Sell` | `1` | Sell a fixed amount of asset. |
272
+ | `Buy` | `2` | Buy a fixed amount of asset. |
88
273
 
89
274
  #### `ClientInitializationParams`
90
275
 
@@ -98,7 +283,7 @@ Parameters passed to the `AxisContractClient` constructor.
98
283
  | `contractId` | `string` | DEX contract id. |
99
284
  | `networkPassphrase?` | `string` | Network passphrase (Pubnet passphrase by default). |
100
285
  | `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). |
286
+ | `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). |
102
287
 
103
288
  #### `SignTransactionCallback`
104
289
 
@@ -107,6 +292,16 @@ Parameters passed to the `AxisContractClient` constructor.
107
292
  Callback for signing transactions generated by the client. Receives the transaction XDR to sign plus the signing
108
293
  context, and resolves to the signed transaction response.
109
294
 
295
+ #### `Approval`
296
+
297
+ Token allowance granted to the contract as part of the call.
298
+
299
+ | Property | Type | Description |
300
+ |---|---|---|
301
+ | `asset?` | `string` | Token the allowance is granted on: defaults to `selling` for `buy`, `sell` and `swap`, required in `update` approvals. |
302
+ | `amount` | `bigint` | Absolute allowance amount (0 revokes the approval). |
303
+ | `liveUntil` | `number` | Ledger sequence the allowance lives until (at most ~180 days ahead). |
304
+
110
305
  #### `TradeArguments`
111
306
 
112
307
  Base arguments shared by `buy` and `sell`.
@@ -118,8 +313,10 @@ Base arguments shared by `buy` and `sell`.
118
313
  | `amount` | `bigint` | Tokens amount. |
119
314
  | `selling` | `string` | Selling token address. |
120
315
  | `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. |
316
+ | `price` | `bigint` | Price a trader is willing to accept (18 decimals). |
317
+ | `orders?` | `bigint[]` | List of order IDs to match before creating the order on-chain. |
318
+ | `expires?` | `bigint \| number` | Expiration UNIX timestamp (seconds) of the order created for a `Limit` remainder, 0 or omitted = none. |
319
+ | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
123
320
 
124
321
  #### `SellTradeArguments`
125
322
 
@@ -157,9 +354,36 @@ Arguments passed to `swap`.
157
354
  | `direction` | `TradeDirection` | Trade direction: `Sell` or `Buy`. |
158
355
  | `trader` | `string` | Trader address. |
159
356
  | `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. |
357
+ | `sellingAmount` | `bigint` | Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`). |
358
+ | `buyingAmount` | `bigint` | Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`). |
162
359
  | `path` | `TradeStep[]` | Ordered list of the trade route steps. |
360
+ | `approve?` | `Approval` | Optional allowance granted to the contract before trading (on `selling` unless `asset` is set). |
361
+
362
+ #### `UpdateArguments`
363
+
364
+ | Property | Type | Description |
365
+ |---|---|---|
366
+ | `trader` | `string` | Orders owner. |
367
+ | `updates` | `OrderUpdate[]` | New amount, price and expiration per order id. |
368
+ | `approvals?` | `Approval[]` | Allowances granted before the backing check, each naming its `asset`; an asset without an approval keeps its current allowance. |
369
+
370
+ #### `OrderUpdate`
371
+
372
+ | Property | Type | Description |
373
+ |---|---|---|
374
+ | `id` | `bigint` | Order id. |
375
+ | `amount` | `bigint` | New amount to sell, `0` removes the order. |
376
+ | `price` | `bigint` | New order price (ignored for a removal). |
377
+ | `expires?` | `bigint \| number` | New expiration UNIX timestamp (seconds), 0 or omitted = none. |
378
+
379
+ #### `SubsidizeArguments`
380
+
381
+ | Property | Type | Description |
382
+ |---|---|---|
383
+ | `sponsor` | `string` | Address paying for the oracle feeds (and the listing fee of a new market). |
384
+ | `selling` | `string` | First market asset. |
385
+ | `buying` | `string` | Second market asset (either order opens the same market). |
386
+ | `amount` | `bigint` | Amount of XRF fee tokens to burn; at least `Config.market_listing_fee` to open a market. |
163
387
 
164
388
  #### `Order`
165
389
 
@@ -167,43 +391,66 @@ Order properties, stored on-chain (returned by `order()` call).
167
391
 
168
392
  | Property | Type | Description |
169
393
  |---|---|---|
170
- | `id` | `bigint` | Order ID. |
171
- | `kind` | `OrderKind` | Trading behavior. |
394
+ | `id` | `bigint` | Order ID, derived from the owner and the client nonce. |
172
395
  | `owner` | `string` | Owner of the order. |
173
396
  | `selling` | `string` | Selling token address. |
174
397
  | `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. |
398
+ | `amount` | `bigint` | Amount left to sell. |
399
+ | `price` | `bigint` | Order price (`buying` per 1 `selling`, 18 decimals). |
400
+ | `expires` | `bigint` | Expiration timestamp (0 = no expiration). |
179
401
 
180
- #### `TradeContractEvent`
402
+ #### `Config`, `Market`, `MarketSide`
181
403
 
182
- Orderbook trade event emitted by the contract.
404
+ Decoded straight from the contract, so field names keep the contract's snake_case:
405
+ `Config {oracle, market_listing_fee, safety_admin, min_trade_size}`, `Market {a, b, created}`,
406
+ `MarketSide {asset, listed, decimals}`. `market_listing_fee` is derived from the oracle (`daily_fee × 90`), never
407
+ supplied: the contract is deployed with `__constructor(safety_admin, oracle, min_trade_size)`.
183
408
 
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. |
409
+ ### Contract events
194
410
 
195
- #### `SwapContractEvent`
411
+ Trading events use the `vec` data format: the event data is a vector of the fields in the order listed. There is no
412
+ trade or swap id; indexers derive one from the ledger, transaction and event position.
196
413
 
197
- Orderbook swap event emitted by the contract.
414
+ | Event | Topics | Data | Notes |
415
+ |---|---|---|---|
416
+ | `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. |
417
+ | `swap` | `swap, selling, buying` | `trader, sold, bought` | One per `swap` call, after the fills of every hop. |
418
+ | `new` | `new, selling, buying` | `id, owner, price, amount, expires` | An order created. `id` is a `u128`, `expires` a `u64` (0 = none). |
419
+ | `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. |
420
+ | `skip` | `skip` | `order: u128` | A listed order its maker could not settle (backing short of the fill, cannot receive the taker's asset, or the transfer failed); the order is left unchanged. Also a `crossfill` taker order its owner cannot back or be paid for. |
421
+ | `refresh` | `refresh, a, b` (market assets in canonical order) | none | Every check of a market against the oracle (`requote`, `subsidize`, market creation). |
422
+ | `freeze` | `freeze` | `frozen: bool` | |
423
+ | `config` | `config` | `Config` | The configuration after the constructor, `delegate`, `set_oracle` or `set_floor`. |
198
424
 
199
- | Property | Type | Description |
425
+ Typed as `TradeContractEvent`, `SwapContractEvent`, `OrderCreatedContractEvent`, `OrderUpdatedContractEvent`,
426
+ `OrderSkippedContractEvent`, `MarketRefreshContractEvent`, `FreezeContractEvent`, `ConfigChangedContractEvent` in
427
+ [`src/index.d.ts`](src/index.d.ts).
428
+
429
+ ### Contract errors
430
+
431
+ Simulation failures caused by the contract are thrown as `Error` with `message` `Contract execution error: #<code>
432
+ <name>` and a numeric `code` property. A transaction that passes simulation but fails on-chain throws an `Error` with
433
+ the transaction `hash` property and the transaction result in its `message`. `ContractErrors` maps the codes:
434
+
435
+ | Code | Name | Meaning |
200
436
  |---|---|---|
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. |
437
+ | 701 | `NotAuthorized` | The caller does not own the order / is not the safety admin. |
438
+ | 702 | `InsufficientBalance` | The order is not backed by the trader's balance. |
439
+ | 703 | `InsufficientAllowance` | The allowance granted to the contract does not cover the order. |
440
+ | 704 | `InvalidMatch` | `selling` equals `buying`, or a `swap` has no path or a non-positive amount (a listed order of another pair is skipped, not an error). |
441
+ | 705 | `InvalidPrice` | Price outside `[1, 10^36]`. |
442
+ | 706 | `InvalidAmount` | An amount is not positive, or a `subsidize` that opens a market is below the listing fee. |
443
+ | 707 | `InvalidExpiration` | An `expires` is neither 0 nor in the future. |
444
+ | 708 | `CannotReceive` | The receiving account cannot accept the asset (missing or deauthorized trustline). |
445
+ | 709 | `NotFilled` | A `FillOrKill` trade or `swap` cannot be executed in full. |
446
+ | 710 | `OrderNotFound` | The order does not exist or has expired. |
447
+ | 711 | `OrderExists` | A live order with the same id exists (retry the call). |
448
+ | 720 | `OrderSizeTooSmall` | Order value below the minimum order size, or the remainder is dust. |
449
+ | 721 | `AssetsNotVerifiedByOracle` | The pair has no market (open it with `subsidize`), or neither asset is listed on the price oracle. |
450
+ | 722 | `AssetPriceOracleFetchFailed` | No listed market asset has a usable cached price: none was fetched by `requote`/`subsidize`, or it is older than 72 hours. |
451
+ | 723 | `InvalidOracleConfig` | The price oracle does not satisfy the contract requirements. |
452
+ | 730 | `Frozen` | Trading is blocked (order removals and approvals still work). |
453
+ | 740 | `Overflow` | A price calculation does not fit i128. Other arithmetic overflows trap as a host error. |
207
454
 
208
455
  ## AxisApiClient
209
456
 
@@ -242,19 +489,24 @@ const {ticker} = await api.getTicker24h()
242
489
 
243
490
  | Method | Description |
244
491
  |---|---|
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). |
492
+ | `quoteSell({sellingAsset, buyingAsset, amount, direct?})` | 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). Throws `AxisApiError` if the server is not ready or there is not enough liquidity. |
493
+ | `quoteBuy({sellingAsset, buyingAsset, amount, direct?})` | Best trade routes for buying a fixed amount of the destination asset (strict receive). Throws like `quoteSell`. |
494
+ | `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. |
248
495
  | `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
496
  | `getTicker24h()` | 24-hour ticker statistics for every available market. |
250
497
  | `getMarkets({cursor?, limit?})` | List all active markets with pagination. |
498
+ | `getContract()` | Contract state tracked by the indexer: `frozen`, `config` (`safetyAdmin`, `oracle`, `marketListingFee`, `minTradeSize`) and active `markets`. |
251
499
  | `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). |
500
+ | `getOrder(id)` | A single active order by ID (throws `AxisApiError` with status 404 if not found). |
501
+ | `getAccount(address)` | Every live order of an account (not paginated) and its backing per traded token. |
253
502
  | `getOrderHistory({owner?, pair?, cursor?, limit?})` | Archived/historical orders (`pair` = `[base, quote]` contract ids). |
254
503
  | `getTrades({trader?, pair?, cursor?, limit?})` | Recent trades (`pair` = `[base, quote]` contract ids). |
255
504
 
256
505
  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.
506
+ `BASE/QUOTE` convention. Amounts are expressed in stroops on input and returned as strings. Order ids are decimal
507
+ strings of the `u128` id; they are not sequential, so pagination uses the `cursor` field of the last received row.
508
+ Orders carry `backed` (the amount the maker can actually deliver) and `backing` when the indexer tracks maker balances
509
+ and allowances.
258
510
 
259
511
  ### Error handling
260
512
 
@@ -274,26 +526,48 @@ try {
274
526
  ## Order footprint
275
527
 
276
528
  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:
529
+ time. The orderbook matching loop stops as soon as the taker is filled, and orders it skipped are recorded read-only
530
+ without their makers' entries. If the book moves before the transaction lands - an order is partly filled, repriced back
531
+ into range, its maker restores the backing, an earlier order shrinks, or an expired order is revived - the contract has
532
+ to read and write entries that are missing from the footprint, resulting in a rejection. Likewise, a `Limit` trade that
533
+ simulation filled in full may create an order for a remainder at apply time under an entry the simulation never saw.
534
+
535
+ To make trading transactions resilient to such changes, `buy`, `sell`, `crossfill` and `swap` patch the simulated
536
+ transaction before signing. Every order id passed in `orders` (plus the taker order id for `crossfill`, every path step
537
+ for `swap`, and the remainder id `orderId(trader, nonce)` for `Limit` trades) is declared in the read-write footprint,
538
+ and so is every entry the settlement may write for the maker behind each listed order: the balance of the asset the
539
+ maker sells, the maker's allowance on it to the contract, and the balance of the asset the maker receives (an account
540
+ entry for XLM, a trustline for a classic asset, the token's `Balance` entry for a contract address; the asset issuer has
541
+ none). The client loads the listed orders and the token instances with one RPC `getLedgerEntries` call (the classic
542
+ asset behind each token is cached per client) and adds entries in list order, orders first, while the footprint limits
543
+ (200 read-write, 400 total) allow. Tokens that are not Stellar Asset Contracts keep what the simulation recorded: their
544
+ storage layout is unknown. The declared instructions, write bytes and resource fee grow with every added entry, and the
545
+ disk read bytes with every added account or trustline entry the simulation did not read; the surplus resource fee is
546
+ refundable, but every declared read-write entry pays the write-entry fee, so routers should list only orders they expect
547
+ to fill. `update` declares the updated order ids only. Pass `autoFootprint: false` to the constructor to opt out.
548
+
549
+ Order entries are keyed by the raw `u128` order id in persistent contract storage and hold a positional vector
550
+ `[owner, selling, buying, amount, price, expires?]`. The helpers exported for custom pipelines:
288
551
 
289
552
  ```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))
553
+ import {orderId} from '@axis-markets/client'
554
+ import {collectOrderIds, completeFootprint} from '@axis-markets/client/footprint'
555
+ import {rpc} from '@stellar/stellar-sdk'
556
+
557
+ // the raw `trade` entry point takes the nonce explicitly - any u64 unique among the owner's live orders
558
+ const nonce = (BigInt(Date.now()) << 22n) | BigInt(crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff)
559
+ const tx = await client.client.trade({...payload, nonce, expires: 0n}, {fee})
560
+ await completeFootprint(tx, contractId, collectOrderIds(payload.orders, [orderId(payload.trader, nonce)]), {
561
+ server: new rpc.Server(rpcUrl),
562
+ tokens: [payload.selling, payload.buying]
563
+ })
294
564
  await tx.signAndSend()
295
565
  ```
296
566
 
567
+ `ensureOrdersFootprint(tx, contractId, orderIds)` declares the order entries alone (no RPC call), and
568
+ `orderLedgerKey`, `balanceLedgerKey`, `allowanceLedgerKey`, `instanceLedgerKey`, `decodeStoredOrder` and
569
+ `decodeSacAsset` build and decode the individual entries.
570
+
297
571
  ## Development
298
572
 
299
573
  Run tests:
@@ -305,7 +579,7 @@ pnpm test
305
579
  Bundling script:
306
580
 
307
581
  ```
308
- npm run prepare
582
+ pnpm run prepare
309
583
  ```
310
584
 
311
585
  Bundles the ESM source (`src/`) into a UMD library (`lib/`) via webpack. Type definitions located in `src/index.d.ts`.