@axis-markets/client 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -100
- package/lib/axis-client.cjs +1 -1
- package/lib/axis-client.cjs.map +1 -1
- package/lib/footprint.cjs +1 -1
- package/lib/footprint.cjs.map +1 -1
- package/package.json +1 -1
- package/src/api-client.js +490 -423
- package/src/api-dates.js +1 -1
- package/src/axis-account.js +1009 -970
- package/src/axis-market.js +181 -197
- package/src/axis.js +409 -408
- package/src/contract-client.js +65 -63
- package/src/errors.js +131 -62
- package/src/footprint.d.ts +129 -102
- package/src/footprint.js +469 -419
- package/src/index.d.ts +347 -167
- package/src/index.js +249 -54
- package/src/order-id.js +47 -47
- package/src/stream-client.js +2 -2
package/README.md
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
JavaScript SDK for [AXIS](https://axis.markets) Stellar DEX.
|
|
4
4
|
|
|
5
|
-
- **`Axis`**, **`AxisMarket`**, **`AxisAccount`**
|
|
6
|
-
trader's open orders and allowances kept in memory from the
|
|
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
7
|
look up the crossing orders and manage allowances automatically.
|
|
8
8
|
- **`AxisContractClient`** — wraps the on-chain AXIS smart contract for order management and trading (sign & send
|
|
9
9
|
transactions, read orders, markets and configuration).
|
|
10
|
-
- **`AxisApiClient`**
|
|
11
|
-
|
|
12
|
-
- **`AxisStreamClient`**
|
|
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
13
|
|
|
14
14
|
## Installation
|
|
15
15
|
|
|
@@ -22,17 +22,25 @@ representation and is not source-compatible with v16).
|
|
|
22
22
|
|
|
23
23
|
## Axis — high-level API
|
|
24
24
|
|
|
25
|
-
`Axis` wrapper follows the contract state (frozen switch, configuration) and every market through the
|
|
26
|
-
|
|
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
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
|
|
28
|
+
spendable balance and allowance in every market token, and trades with automatic allowance management. The AXIS API's
|
|
29
29
|
data source streams updates for that state to maintain consistent up-to-date state in memory.
|
|
30
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
|
+
|
|
31
34
|
```js
|
|
32
35
|
import {Axis, TradeDirection} from '@axis-markets/client'
|
|
33
36
|
|
|
37
|
+
//testnet token contracts
|
|
38
|
+
const XLM = 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC'
|
|
39
|
+
const USDC = 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA' //USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5
|
|
40
|
+
const EURC = 'CCUUDM434BMZMYWYDITHFXHDMIVTGGD6T2I5UKNX5BSLXLW7HVR4MCGZ'
|
|
41
|
+
|
|
34
42
|
const axis = new Axis({
|
|
35
|
-
apiUrl: 'https://
|
|
43
|
+
apiUrl: 'https://demo-api.axis.markets',
|
|
36
44
|
rpcUrl: 'https://soroban-testnet.stellar.org',
|
|
37
45
|
contractId: 'CBJ747MKAGQO2LMJPOTCOONAWBLIIBSLOQE325R457TE5MIS6RTDJ4DC',
|
|
38
46
|
networkPassphrase: 'Test SDF Network ; September 2015'
|
|
@@ -40,7 +48,7 @@ const axis = new Axis({
|
|
|
40
48
|
await axis.connect()
|
|
41
49
|
axis.on('frozen', frozen => console.log('trading', frozen ? 'suspended' : 'resumed'))
|
|
42
50
|
|
|
43
|
-
const market = axis.getMarket(XLM, USDC) // either order: market.
|
|
51
|
+
const market = axis.getMarket(XLM, USDC) // either order: market.base / market.quote are in the contract order
|
|
44
52
|
|
|
45
53
|
const account = axis.account(publicKey, {signTransaction})
|
|
46
54
|
await account.ready
|
|
@@ -49,6 +57,8 @@ account.on('filled', ({order}) => console.log(`order ${order.id} filled`))
|
|
|
49
57
|
account.on('expire', order => console.log(`order ${order.id} expired`))
|
|
50
58
|
account.on('backing', ({asset}) => console.log(asset, 'balance', account.getBalance(asset)))
|
|
51
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})
|
|
52
62
|
// limit sell of 100 XLM at 0.25 USDC; crossing orders and the approval are handled by the account
|
|
53
63
|
const {sold, bought, orderId} = await account.sell({
|
|
54
64
|
selling: XLM,
|
|
@@ -71,7 +81,7 @@ is down, the token is not tracked, or for 30 s after this client spent the token
|
|
|
71
81
|
spend may lag behind). An order this client created counts as committed right away (`pending: true`) until the indexer
|
|
72
82
|
reports it.
|
|
73
83
|
|
|
74
|
-
**Balances.** While an account is subscribed, the
|
|
84
|
+
**Balances.** While an account is subscribed, the AXIS API tracks it in every market token.
|
|
75
85
|
`account.balances` / `getBalance(asset)` give the spendable amount, and each change emits
|
|
76
86
|
`backing` event.
|
|
77
87
|
|
|
@@ -82,19 +92,19 @@ selling the token oldest first), `backedPct` and `backingPending`.
|
|
|
82
92
|
| `Axis` | Description |
|
|
83
93
|
|---|---|
|
|
84
94
|
| `connect()` | Load the contract state and follow its changes. |
|
|
85
|
-
| `ledger`, `getLedger()` | Last ledger pushed by the
|
|
95
|
+
| `ledger`, `getLedger()` | Last ledger pushed by the AXIS API; current ledger (pushed, or RPC when stale). |
|
|
86
96
|
| `frozen`, `config`, `markets`, `loaded` | Contract state; `markets` is a `Map` of `AxisMarket` by canonical key. |
|
|
87
97
|
| `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
|
|
98
|
+
| `getOrder(id)` | Live order from a tracked account's memory or the AXIS API, `undefined` if gone. |
|
|
89
99
|
| `account(address, {signTransaction})` | `AxisAccount` of the trader (one per address). |
|
|
90
100
|
| `subscribeTicker(cb)` | 24h ticker of every market (canonical orientation); also fills `market.ticker`. |
|
|
91
|
-
| `keepalive(signer?)` | Extend the contract instance and code lifetime. |
|
|
101
|
+
| `keepalive({days?, signer?})` | Extend the contract instance and code lifetime, see `AxisContractClient.keepalive`. |
|
|
92
102
|
| `close()` | Stop following the contract and every account. |
|
|
93
103
|
| events | `change`, `frozen`, `config`, `market` (`{market, created}`), `connection`, `ledger` |
|
|
94
104
|
|
|
95
105
|
| `AxisMarket` | Description |
|
|
96
106
|
|---|---|
|
|
97
|
-
| `
|
|
107
|
+
| `base`, `quote`, `key`, `created`, `refreshed` | Canonical assets (the contract's `base` and `quote`), the `base/quote` key and oracle check times. |
|
|
98
108
|
| `requote(signer?)` | Re-check the market against the oracle and cache prices (submits nothing when nothing changed). |
|
|
99
109
|
| `subsidize({amount, sponsor?, signer?})` | Extend the oracle feeds access of the market. |
|
|
100
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. |
|
|
@@ -107,11 +117,12 @@ selling the token oldest first), `backedPct` and `backingPending`.
|
|
|
107
117
|
| `balances`, `getBalance(asset)`, `funded` | Spendable balances by token (every market token), whether the account exists. |
|
|
108
118
|
| `getOrders({market?, selling?, buying?})` | Open orders, newest first, including `pending` ones this client created. |
|
|
109
119
|
| `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?}`. |
|
|
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). |
|
|
111
122
|
| `update(updates)` | Change orders (omitted fields keep their values). |
|
|
112
123
|
| `cancel(ids)`, `cancelAll({market?})` | Remove orders (batches of 100). |
|
|
113
124
|
| `crossfill(takerOrderId, orders?)` | Fill an open order against the book. |
|
|
114
|
-
| `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best
|
|
125
|
+
| `swap({selling, buying, amount, direction?, slippage?})` | Swap along the best AXIS API route. |
|
|
115
126
|
| events | `ready`, `new`, `pending`, `fill`, `filled`, `update`, `cancel`, `expire`, `remove`, `order`, `backing`, `approve`, `trade`, `swap`, `change`, `error` |
|
|
116
127
|
|
|
117
128
|
## AxisContractClient
|
|
@@ -119,27 +130,31 @@ selling the token oldest first), `backedPct` and `backingPending`.
|
|
|
119
130
|
Wraps the on-chain AXIS smart contract for trading and order management.
|
|
120
131
|
|
|
121
132
|
```js
|
|
133
|
+
import {Networks, rpc} from '@stellar/stellar-sdk'
|
|
122
134
|
import {AxisContractClient, OrderKind, TradeDirection} from '@axis-markets/client'
|
|
123
135
|
|
|
136
|
+
const rpcUrl = 'https://soroban-testnet.stellar.org'
|
|
124
137
|
const client = new AxisContractClient({
|
|
125
138
|
publicKey: 'G...', // trader public key
|
|
126
|
-
contractId: '
|
|
127
|
-
rpcUrl
|
|
128
|
-
|
|
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}
|
|
129
143
|
})
|
|
144
|
+
const {sequence} = await new rpc.Server(rpcUrl).getLatestLedger()
|
|
130
145
|
|
|
131
146
|
// Place a sell limit order (the remainder becomes a limit order if not fully executed).
|
|
132
147
|
// The id of the created order, if any, is returned as the third tuple element.
|
|
133
148
|
const [sold, bought, newOrderId] = await client.sell({
|
|
134
149
|
kind: OrderKind.Limit,
|
|
135
150
|
trader: 'G...',
|
|
136
|
-
amount:
|
|
137
|
-
selling: '
|
|
138
|
-
buying: '
|
|
139
|
-
price:
|
|
140
|
-
orders: [], // maker order ids to cross first (from
|
|
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)
|
|
141
156
|
expires: Math.floor(Date.now() / 1000) + 86_400, // optional expiration of the created order (UNIX seconds)
|
|
142
|
-
approve: {amount:
|
|
157
|
+
approve: {amount: 100_000_000n, liveUntil: sequence + 518_400} // optional in-call allowance on `selling` (~30 days)
|
|
143
158
|
})
|
|
144
159
|
|
|
145
160
|
// Fetch an order by id
|
|
@@ -150,8 +165,8 @@ await client.update({
|
|
|
150
165
|
trader: 'G...',
|
|
151
166
|
updates: [{
|
|
152
167
|
id: newOrderId,
|
|
153
|
-
amount:
|
|
154
|
-
price:
|
|
168
|
+
amount: 50_000_000n,
|
|
169
|
+
price: 51n * 10n ** 16n, // 0.51 USDC per XLM
|
|
155
170
|
expires: Math.floor(Date.now() / 1000) + 7 * 86_400
|
|
156
171
|
}]
|
|
157
172
|
})
|
|
@@ -172,21 +187,25 @@ See [`src/index.d.ts`](src/index.d.ts) for the full typed API.
|
|
|
172
187
|
| `getMarket(selling, buying)` | Fetch the market record for an asset pair, either order (contract `market`). Returns `Promise<Market \| undefined>`. |
|
|
173
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]>`. |
|
|
174
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]>`. |
|
|
175
|
-
| `
|
|
176
|
-
| `
|
|
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 90 orders per. 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 90 orders per call. |
|
|
177
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`. |
|
|
178
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]>`. |
|
|
179
|
-
| `keepalive()` | Extend the contract instance and code lifetime to
|
|
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. |
|
|
180
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). |
|
|
181
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. |
|
|
182
198
|
|
|
183
199
|
Standalone helper: `orderId(owner, nonce)` (see below).
|
|
184
200
|
|
|
185
|
-
The safety admin entry points (`freeze`, `delegate`, `set_oracle`, `set_floor`
|
|
186
|
-
outside the client.
|
|
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.
|
|
187
203
|
|
|
188
|
-
|
|
189
|
-
|
|
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.
|
|
190
209
|
|
|
191
210
|
### Markets and prices
|
|
192
211
|
|
|
@@ -200,15 +219,19 @@ of the assets to be quoted by the price oracle:
|
|
|
200
219
|
nothing is left). The sponsor signs both `track` calls and their XRF `burn` sub-invocations and never burns more than
|
|
201
220
|
`amount`.
|
|
202
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`).
|
|
203
223
|
|
|
204
|
-
The listing fee is
|
|
205
|
-
|
|
206
|
-
|
|
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.
|
|
207
228
|
|
|
208
229
|
`buy`, `sell` and `update` never call the oracle. They value orders against the prices cached by `requote` and
|
|
209
230
|
`subsidize`, on the selling asset when it is listed and priced and otherwise on the buying asset; no usable price on
|
|
210
231
|
either listed asset (missing or older than 72 hours) fails with `AssetPriceOracleFetchFailed` (`722`). Keepers call
|
|
211
|
-
`requote(
|
|
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.
|
|
212
235
|
|
|
213
236
|
### Order expiration
|
|
214
237
|
|
|
@@ -221,12 +244,25 @@ order expires.
|
|
|
221
244
|
|
|
222
245
|
### Allowances
|
|
223
246
|
|
|
224
|
-
The contract holds no user funds. Every asset a trader sells through AXIS needs a standing allowance
|
|
225
|
-
contract on the token (`approve(from = trader, spender = AXIS, amount, liveUntil)`)
|
|
226
|
-
`transfer_from
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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.
|
|
230
266
|
|
|
231
267
|
Pass `approve: {amount, liveUntil}` to `buy`, `sell` or `swap` to grant (or reset) the allowance on the selling asset as
|
|
232
268
|
part of the same transaction (set `asset` to approve another token). `update` takes a separate
|
|
@@ -234,9 +270,9 @@ part of the same transaction (set `asset` to approve another token). `update` ta
|
|
|
234
270
|
current allowance, and a zero amount revokes. The amount is absolute, not a delta, so the signed authorization does not
|
|
235
271
|
depend on ledger state; when several approvals name the same asset, the last one wins. `cancel` never moves tokens.
|
|
236
272
|
|
|
237
|
-
### Order
|
|
273
|
+
### Order IDs and nonces
|
|
238
274
|
|
|
239
|
-
An order
|
|
275
|
+
An order ID is chosen by the client through a `u64` nonce:
|
|
240
276
|
|
|
241
277
|
```
|
|
242
278
|
id = u128::from_be_bytes(sha256(xdr(ScVec[owner: Address, nonce: u64]))[0..16])
|
|
@@ -282,15 +318,18 @@ Parameters passed to the `AxisContractClient` constructor.
|
|
|
282
318
|
| `rpcUrl` | `string` | URL of the RPC server. |
|
|
283
319
|
| `contractId` | `string` | DEX contract id. |
|
|
284
320
|
| `networkPassphrase?` | `string` | Network passphrase (Pubnet passphrase by default). |
|
|
285
|
-
| `fee?` | `string` |
|
|
321
|
+
| `fee?` | `string` | Inclusion fee bid in stroops (`'100000'`, 0.01 XLM, by default). The resource fee from simulation is added on top. |
|
|
286
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). |
|
|
287
323
|
|
|
288
324
|
#### `SignTransactionCallback`
|
|
289
325
|
|
|
290
|
-
`(
|
|
326
|
+
`(xdr: string, opts?: {networkPassphrase?, address?, submit?, submitUrl?}) => Promise<{signedTxXdr, signerAddress?, error?}>`
|
|
291
327
|
|
|
292
|
-
Callback for signing transactions generated by the client
|
|
293
|
-
|
|
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()}`.
|
|
294
333
|
|
|
295
334
|
#### `Approval`
|
|
296
335
|
|
|
@@ -397,14 +436,18 @@ Order properties, stored on-chain (returned by `order()` call).
|
|
|
397
436
|
| `buying` | `string` | Buying token address. |
|
|
398
437
|
| `amount` | `bigint` | Amount left to sell. |
|
|
399
438
|
| `price` | `bigint` | Order price (`buying` per 1 `selling`, 18 decimals). |
|
|
400
|
-
| `expires` | `bigint` | Expiration timestamp (0 = no expiration). |
|
|
439
|
+
| `expires` | `bigint` | Expiration UNIX timestamp in seconds (0 = no expiration). |
|
|
401
440
|
|
|
402
441
|
#### `Config`, `Market`, `MarketSide`
|
|
403
442
|
|
|
404
443
|
Decoded straight from the contract, so field names keep the contract's snake_case:
|
|
405
|
-
`Config {oracle,
|
|
406
|
-
`
|
|
407
|
-
|
|
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.
|
|
408
451
|
|
|
409
452
|
### Contract events
|
|
410
453
|
|
|
@@ -413,14 +456,14 @@ trade or swap id; indexers derive one from the ledger, transaction and event pos
|
|
|
413
456
|
|
|
414
457
|
| Event | Topics | Data | Notes |
|
|
415
458
|
|---|---|---|---|
|
|
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. |
|
|
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. |
|
|
417
460
|
| `swap` | `swap, selling, buying` | `trader, sold, bought` | One per `swap` call, after the fills of every hop. |
|
|
418
461
|
| `new` | `new, selling, buying` | `id, owner, price, amount, expires` | An order created. `id` is a `u128`, `expires` a `u64` (0 = none). |
|
|
419
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. |
|
|
420
|
-
| `skip` | `skip` | `order: u128` | A listed order its maker could not settle (backing short of the fill,
|
|
421
|
-
| `refresh` | `refresh,
|
|
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). |
|
|
422
465
|
| `freeze` | `freeze` | `frozen: bool` | |
|
|
423
|
-
| `config` | `config` | `Config` | The configuration after the constructor, `delegate`, `set_oracle` or `
|
|
466
|
+
| `config` | `config` | `Config` | The configuration after the constructor, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days` or `set_ledger_time`. |
|
|
424
467
|
|
|
425
468
|
Typed as `TradeContractEvent`, `SwapContractEvent`, `OrderCreatedContractEvent`, `OrderUpdatedContractEvent`,
|
|
426
469
|
`OrderSkippedContractEvent`, `MarketRefreshContractEvent`, `FreezeContractEvent`, `ConfigChangedContractEvent` in
|
|
@@ -429,57 +472,71 @@ Typed as `TradeContractEvent`, `SwapContractEvent`, `OrderCreatedContractEvent`,
|
|
|
429
472
|
### Contract errors
|
|
430
473
|
|
|
431
474
|
Simulation failures caused by the contract are thrown as `Error` with `message` `Contract execution error: #<code>
|
|
432
|
-
<name>` and a numeric `code` property. A
|
|
433
|
-
the
|
|
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:
|
|
434
481
|
|
|
435
482
|
| Code | Name | Meaning |
|
|
436
483
|
|---|---|---|
|
|
437
|
-
| 701 | `NotAuthorized` |
|
|
484
|
+
| 701 | `NotAuthorized` | An `update` or `cancel` lists an order that `trader` does not own. |
|
|
438
485
|
| 702 | `InsufficientBalance` | The order is not backed by the trader's balance. |
|
|
439
486
|
| 703 | `InsufficientAllowance` | The allowance granted to the contract does not cover the order. |
|
|
440
|
-
| 704 | `InvalidMatch` | `selling` equals `buying
|
|
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). |
|
|
441
488
|
| 705 | `InvalidPrice` | Price outside `[1, 10^36]`. |
|
|
442
|
-
| 706 | `InvalidAmount` | An amount is not positive,
|
|
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. |
|
|
443
490
|
| 707 | `InvalidExpiration` | An `expires` is neither 0 nor in the future. |
|
|
444
|
-
| 708 | `CannotReceive` | The
|
|
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. |
|
|
445
492
|
| 709 | `NotFilled` | A `FillOrKill` trade or `swap` cannot be executed in full. |
|
|
446
493
|
| 710 | `OrderNotFound` | The order does not exist or has expired. |
|
|
447
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. |
|
|
448
496
|
| 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
|
|
451
|
-
| 723 | `InvalidOracleConfig` | The price oracle does not satisfy the contract requirements. |
|
|
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). |
|
|
452
500
|
| 730 | `Frozen` | Trading is blocked (order removals and approvals still work). |
|
|
453
|
-
| 740 | `Overflow` |
|
|
501
|
+
| 740 | `Overflow` | An arithmetic invariant was violated. Other arithmetic overflows trap as a host error. |
|
|
454
502
|
|
|
455
503
|
## AxisApiClient
|
|
456
504
|
|
|
457
|
-
HTTP client for the AXIS
|
|
505
|
+
HTTP client for the AXIS REST API. Uses the standard `fetch` API - no extra dependencies.
|
|
458
506
|
|
|
459
507
|
```js
|
|
460
508
|
import {AxisApiClient, AxisApiError} from '@axis-markets/client'
|
|
461
509
|
|
|
462
|
-
const api = new AxisApiClient('https://
|
|
510
|
+
const api = new AxisApiClient('https://demo-api.axis.markets') // testnet
|
|
511
|
+
const USDC = 'USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' // testnet USDC
|
|
463
512
|
|
|
464
513
|
// Quote: sell a fixed amount of the source asset (strict send)
|
|
465
514
|
const sellQuote = await api.quoteSell({
|
|
466
515
|
sellingAsset: 'XLM',
|
|
467
|
-
buyingAsset:
|
|
516
|
+
buyingAsset: USDC,
|
|
468
517
|
amount: '10000000' // stroops (1 unit = 10,000,000 stroops)
|
|
469
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
|
+
}
|
|
470
522
|
|
|
471
523
|
// Quote: buy a fixed amount of the destination asset (strict receive)
|
|
472
524
|
const buyQuote = await api.quoteBuy({
|
|
473
525
|
sellingAsset: 'XLM',
|
|
474
|
-
buyingAsset:
|
|
526
|
+
buyingAsset: USDC,
|
|
475
527
|
amount: '5000000'
|
|
476
528
|
})
|
|
477
529
|
|
|
478
530
|
// Order book depth around the mid price
|
|
479
|
-
const depth = await api.getDepth({market:
|
|
480
|
-
|
|
481
|
-
// OHLCVT candles
|
|
482
|
-
const candles = await api.getCandles({
|
|
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
|
+
})
|
|
483
540
|
|
|
484
541
|
// 24h ticker for every market
|
|
485
542
|
const {ticker} = await api.getTicker24h()
|
|
@@ -489,24 +546,30 @@ const {ticker} = await api.getTicker24h()
|
|
|
489
546
|
|
|
490
547
|
| Method | Description |
|
|
491
548
|
|---|---|
|
|
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).
|
|
493
|
-
| `quoteBuy({sellingAsset, buyingAsset, amount, direct?})` | Best trade routes for buying a fixed amount of the destination asset (strict receive).
|
|
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`. |
|
|
494
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. |
|
|
495
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`). |
|
|
496
553
|
| `getTicker24h()` | 24-hour ticker statistics for every available market. |
|
|
497
|
-
| `getMarkets({cursor?, limit?})` |
|
|
498
|
-
| `getContract()` | Contract state tracked by the indexer: `frozen`, `config` (`safetyAdmin`, `oracle`, `marketListingFee`, `minTradeSize`) and active `markets
|
|
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`). |
|
|
499
556
|
| `getOrders({owner?, asset?, cursor?, limit?})` | Active orders, filterable by owner or asset (`asset` may be a string or string array). |
|
|
500
557
|
| `getOrder(id)` | A single active order by ID (throws `AxisApiError` with status 404 if not found). |
|
|
501
558
|
| `getAccount(address)` | Every live order of an account (not paginated) and its backing per traded token. |
|
|
502
|
-
| `getOrderHistory({owner?, pair?, cursor?, limit?})` | Archived/historical orders (`pair` = `[base, quote]` contract ids). |
|
|
503
|
-
| `getTrades({trader?, pair?, cursor?, limit?})` | Recent trades (`pair` = `[base, quote]` contract ids). |
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
`
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
and
|
|
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).
|
|
510
573
|
|
|
511
574
|
### Error handling
|
|
512
575
|
|
|
@@ -535,16 +598,19 @@ simulation filled in full may create an order for a remainder at apply time unde
|
|
|
535
598
|
To make trading transactions resilient to such changes, `buy`, `sell`, `crossfill` and `swap` patch the simulated
|
|
536
599
|
transaction before signing. Every order id passed in `orders` (plus the taker order id for `crossfill`, every path step
|
|
537
600
|
for `swap`, and the remainder id `orderId(trader, nonce)` for `Limit` trades) is declared in the read-write footprint,
|
|
538
|
-
and so
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
asset
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
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.
|
|
548
614
|
|
|
549
615
|
Order entries are keyed by the raw `u128` order id in persistent contract storage and hold a positional vector
|
|
550
616
|
`[owner, selling, buying, amount, price, expires?]`. The helpers exported for custom pipelines:
|
|
@@ -559,7 +625,10 @@ const nonce = (BigInt(Date.now()) << 22n) | BigInt(crypto.getRandomValues(new Ui
|
|
|
559
625
|
const tx = await client.client.trade({...payload, nonce, expires: 0n}, {fee})
|
|
560
626
|
await completeFootprint(tx, contractId, collectOrderIds(payload.orders, [orderId(payload.trader, nonce)]), {
|
|
561
627
|
server: new rpc.Server(rpcUrl),
|
|
562
|
-
tokens: [payload.selling, payload.buying]
|
|
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
|
|
563
632
|
})
|
|
564
633
|
await tx.signAndSend()
|
|
565
634
|
```
|