@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/src/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {Networks, contract, rpc} from '@stellar/stellar-sdk'
|
|
1
|
+
import {Contract, Networks, Operation, SorobanDataBuilder, TransactionBuilder, contract, rpc, xdr} from '@stellar/stellar-sdk'
|
|
2
2
|
import ContractClient from './contract-client.js'
|
|
3
|
-
import {ContractErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
|
|
3
|
+
import {ContractErrors, TokenErrors, processSimulationErrors, processTransactionErrors} from './errors.js'
|
|
4
4
|
import {AxisApiClient, AxisApiError} from './api-client.js'
|
|
5
5
|
import {collectOrderIds, completeFootprint, ensureOrdersFootprint} from './footprint.js'
|
|
6
6
|
import {orderId, generateNonce} from './order-id.js'
|
|
7
7
|
import {OrderKind, TradeDirection} from './constants.js'
|
|
8
8
|
|
|
9
|
-
export {ContractErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}
|
|
9
|
+
export {ContractErrors, TokenErrors, AxisApiClient, AxisApiError, orderId, OrderKind, TradeDirection}
|
|
10
10
|
export {Axis, toWsUrl} from './axis.js'
|
|
11
11
|
export {AxisMarket} from './axis-market.js'
|
|
12
12
|
export {AxisAccount, parseApiOrder} from './axis-account.js'
|
|
@@ -17,6 +17,14 @@ export {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS, APPROVAL_RENEW_LEDGER
|
|
|
17
17
|
export {canonicalPair, compareAssets, pairKey, invertPrice, invertTicker, PRICE_SCALE} from './asset-pair.js'
|
|
18
18
|
export {parseApiDate} from './api-dates.js'
|
|
19
19
|
|
|
20
|
+
const SECONDS_PER_DAY = 86_400
|
|
21
|
+
//ledger close time assumed when the contract configuration cannot be read, in seconds (the contract's default)
|
|
22
|
+
const DEFAULT_LEDGER_TIME = 5
|
|
23
|
+
//default lifetime `keepalive` extends the contract instance and code to, in days
|
|
24
|
+
const KEEPALIVE_DAYS = 30
|
|
25
|
+
//validity window of transactions built by the client, in seconds
|
|
26
|
+
const TX_TIMEOUT = 60
|
|
27
|
+
|
|
20
28
|
/**
|
|
21
29
|
* Smart contract client for trading with AXIS DEX
|
|
22
30
|
*/
|
|
@@ -96,7 +104,8 @@ export class AxisContractClient {
|
|
|
96
104
|
* @param {BuyTradeArguments} params
|
|
97
105
|
* @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
|
|
98
106
|
* @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
|
|
99
|
-
* no reference price is available,
|
|
107
|
+
* no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
|
|
108
|
+
* cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
|
|
100
109
|
*/
|
|
101
110
|
async buy(params) {
|
|
102
111
|
return await execTrade(params, TradeDirection.Buy, this)
|
|
@@ -107,22 +116,43 @@ export class AxisContractClient {
|
|
|
107
116
|
* @param {SellTradeArguments} params
|
|
108
117
|
* @return {Promise<[bigint, bigint, bigint|undefined]>} - Amount of sold and bought tokens, ID of the newly created order if any
|
|
109
118
|
* @throws {Error} - If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
|
|
110
|
-
* no reference price is available,
|
|
119
|
+
* no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
|
|
120
|
+
* cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
|
|
111
121
|
*/
|
|
112
122
|
async sell(params) {
|
|
113
123
|
return await execTrade(params, TradeDirection.Sell, this)
|
|
114
124
|
}
|
|
115
125
|
|
|
126
|
+
/**
|
|
127
|
+
* Simulate a buy trade without signing or submitting it, to show the network fee before the trade.
|
|
128
|
+
* @param {BuyTradeArguments} params
|
|
129
|
+
* @return {Promise<TradeEstimate>}
|
|
130
|
+
* @throws {Error} - If the simulation fails, for the same reasons as `buy`
|
|
131
|
+
*/
|
|
132
|
+
async estimateBuy(params) {
|
|
133
|
+
return estimateTx(await prepareTrade(params, TradeDirection.Buy, this), this.fee)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Simulate a sell trade without signing or submitting it, to show the network fee before the trade.
|
|
138
|
+
* @param {SellTradeArguments} params
|
|
139
|
+
* @return {Promise<TradeEstimate>}
|
|
140
|
+
* @throws {Error} - If the simulation fails, for the same reasons as `sell`
|
|
141
|
+
*/
|
|
142
|
+
async estimateSell(params) {
|
|
143
|
+
return estimateTx(await prepareTrade(params, TradeDirection.Sell, this), this.fee)
|
|
144
|
+
}
|
|
145
|
+
|
|
116
146
|
/**
|
|
117
147
|
* Update the amount, price, or expiration of several orders in place, or remove them.
|
|
118
148
|
* Orders that no longer exist are skipped; expired orders revived with the new expiration.
|
|
119
|
-
* A zero amount removes the order, expired ones included. An updated order's entry lifetime is
|
|
120
|
-
*
|
|
121
|
-
* A transaction can process up to
|
|
149
|
+
* A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover its expiration +1 day.
|
|
150
|
+
* Approvals and removals work in a frozen contract and on a market without quoted assets.
|
|
151
|
+
* A transaction can process up to 90 orders in one batch.
|
|
122
152
|
* @param {UpdateArguments} params
|
|
123
153
|
* @return {Promise<bigint[]>} - IDs of the orders to update
|
|
124
154
|
* @throws {Error} - If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,
|
|
125
|
-
* if the new amounts are not backed by the trader's balance and allowance,
|
|
155
|
+
* if the new amounts are not backed by the trader's balance and allowance, an update changes an order on the frozen or not-quoted market
|
|
126
156
|
*/
|
|
127
157
|
async update(params) {
|
|
128
158
|
const updates = params.updates.map(update => ({
|
|
@@ -144,11 +174,11 @@ export class AxisContractClient {
|
|
|
144
174
|
}
|
|
145
175
|
|
|
146
176
|
/**
|
|
147
|
-
* Cancel existing orders, expired ones included. A transaction can process up to
|
|
177
|
+
* Cancel existing orders, expired ones included. A transaction can process up to 90 orders in one batch.
|
|
148
178
|
* @param {string} trader - Trader address
|
|
149
179
|
* @param {bigint[]} ids - IDs of the orders to cancel (non-existent orders are ignored)
|
|
150
180
|
* @return {Promise<void>}
|
|
151
|
-
* @throws {Error} - If trader is not the owner of any existing order in `ids`
|
|
181
|
+
* @throws {Error} - If trader is not the owner of any existing order in `ids` (works while the contract is frozen)
|
|
152
182
|
*/
|
|
153
183
|
async cancel(trader, ids) {
|
|
154
184
|
await this.update({trader, updates: ids.map(id => ({id, amount: 0n, price: 0n}))})
|
|
@@ -159,15 +189,16 @@ export class AxisContractClient {
|
|
|
159
189
|
* @param {string} trader - Trader address
|
|
160
190
|
* @param {bigint} takerOrderId - ID of the order that serves as a taker
|
|
161
191
|
* @param {bigint[]} orders - List of order IDs to match against
|
|
162
|
-
* @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the
|
|
163
|
-
* @throws {Error} - If the taker order does not exist or has expired, if
|
|
164
|
-
*
|
|
192
|
+
* @return {Promise<[bigint, bigint, bigint]>} - Amount the taker order sold, amount the makers delivered, surplus paid to the trader.
|
|
193
|
+
* @throws {Error} - If the taker order does not exist or has expired, if the trader cannot receive the bought asset, if the
|
|
194
|
+
* contract cannot hold the bought asset, if the contract is frozen.
|
|
165
195
|
*/
|
|
166
196
|
async crossfill(trader, takerOrderId, orders) {
|
|
167
197
|
const tx = await this.client.crossfill({trader, taker_order_id: takerOrderId, orders}, {fee: this.fee})
|
|
168
198
|
processSimulationErrors(tx)
|
|
169
|
-
//the traded assets come from the taker order, resolved while completing the footprint
|
|
170
|
-
|
|
199
|
+
//the traded assets come from the taker order, resolved while completing the footprint: what it buys passes
|
|
200
|
+
//through the contract, which pays the owner and the surplus to the trader
|
|
201
|
+
await this.updateTradeFootprint(tx, {takerOrder: takerOrderId, receiver: trader}, [takerOrderId], orders)
|
|
171
202
|
const result = await signAndSend(tx)
|
|
172
203
|
return [result[0], result[1], result[2]]
|
|
173
204
|
}
|
|
@@ -177,7 +208,7 @@ export class AxisContractClient {
|
|
|
177
208
|
* @param {SwapArguments} params
|
|
178
209
|
* @return {Promise<[bigint, bigint]>} - Amount of sold and bought tokens
|
|
179
210
|
* @throws {Error} - If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,
|
|
180
|
-
* if
|
|
211
|
+
* if the contract cannot hold an asset of the path, if the contract is frozen.
|
|
181
212
|
*/
|
|
182
213
|
async swap(params) {
|
|
183
214
|
const tx = await this.client.swap({
|
|
@@ -190,8 +221,14 @@ export class AxisContractClient {
|
|
|
190
221
|
approve: toApproval(params.approve, params.selling)
|
|
191
222
|
}, {fee: this.fee})
|
|
192
223
|
processSimulationErrors(tx)
|
|
193
|
-
const
|
|
194
|
-
|
|
224
|
+
const hops = params.path.map(step => step.asset)
|
|
225
|
+
//every hop asset passes through the contract, the last one is forwarded to the trader
|
|
226
|
+
await this.updateTradeFootprint(tx, {
|
|
227
|
+
tokens: [params.selling, ...hops],
|
|
228
|
+
passThrough: hops,
|
|
229
|
+
receiver: params.trader,
|
|
230
|
+
bought: hops[hops.length - 1]
|
|
231
|
+
}, ...params.path.map(step => step.orders))
|
|
195
232
|
const result = await signAndSend(tx)
|
|
196
233
|
return [result[0], result[1]]
|
|
197
234
|
}
|
|
@@ -221,8 +258,8 @@ export class AxisContractClient {
|
|
|
221
258
|
* Extend oracle price feeds access for a market, creating the market if it does not exist yet.
|
|
222
259
|
* @param {SubsidizeArguments} params
|
|
223
260
|
* @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) per oracle-listed asset
|
|
224
|
-
* @throws {Error} - If `amount` is invalid, if the market does not exist and the amount is below
|
|
225
|
-
* if neither market asset is quoted by the oracle, if the contract is frozen
|
|
261
|
+
* @throws {Error} - If `amount` is invalid, if `selling` equals `buying`, if the market does not exist and the amount is below
|
|
262
|
+
* the market listing fee, if neither market asset is quoted by the oracle, if the contract is frozen
|
|
226
263
|
*/
|
|
227
264
|
async subsidize(params) {
|
|
228
265
|
const tx = await this.client.subsidize({
|
|
@@ -237,13 +274,65 @@ export class AxisContractClient {
|
|
|
237
274
|
}
|
|
238
275
|
|
|
239
276
|
/**
|
|
240
|
-
* Extend the contract instance and code lifetime
|
|
241
|
-
*
|
|
277
|
+
* Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived
|
|
278
|
+
* ones first with a `RestoreFootprint` transaction.
|
|
279
|
+
* @param {number} [days] - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)
|
|
280
|
+
* @return {Promise<number>} - Ledger sequence both entries live at least until
|
|
281
|
+
* @throws {Error} - If `days` is invalid, if the instance is not found, if a simulation or a transaction fails
|
|
242
282
|
*/
|
|
243
|
-
async keepalive() {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
await
|
|
283
|
+
async keepalive(days = KEEPALIVE_DAYS) {
|
|
284
|
+
if (!Number.isInteger(days) || days <= 0)
|
|
285
|
+
throw new TypeError(`Invalid keepalive days: ${days}`)
|
|
286
|
+
const {keys, archived} = await contractLifetimeEntries(this.server, this.client.options.contractId)
|
|
287
|
+
if (archived.length)
|
|
288
|
+
await this.submitFootprintOperation(Operation.restoreFootprint({}), new SorobanDataBuilder().setReadWrite(archived))
|
|
289
|
+
//read after the restoration: the configuration is stored in the instance
|
|
290
|
+
const extendTo = Math.ceil(days * SECONDS_PER_DAY / await this.loadLedgerTime())
|
|
291
|
+
const simulation = await this.submitFootprintOperation(Operation.extendFootprintTtl({extendTo}), new SorobanDataBuilder().setReadOnly(keys))
|
|
292
|
+
return simulation.latestLedger + extendTo
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Build, simulate, sign and submit a transaction with a single footprint operation (`ExtendFootprintTTL` or `RestoreFootprint`)
|
|
297
|
+
* @param {xdr.Operation} operation
|
|
298
|
+
* @param {SorobanDataBuilder} sorobanData - Footprint of the operation
|
|
299
|
+
* @return {Promise<rpc.Api.SimulateTransactionSuccessResponse>} - Simulation the submitted transaction was assembled from
|
|
300
|
+
* @private
|
|
301
|
+
*/
|
|
302
|
+
async submitFootprintOperation(operation, sorobanData) {
|
|
303
|
+
const {networkPassphrase, signTransaction} = this.client.options
|
|
304
|
+
const tx = new TransactionBuilder(await this.server.getAccount(this.publicKey), {fee: this.fee, networkPassphrase})
|
|
305
|
+
.addOperation(operation)
|
|
306
|
+
.setSorobanData(sorobanData.build())
|
|
307
|
+
.setTimeout(TX_TIMEOUT)
|
|
308
|
+
.build()
|
|
309
|
+
const simulation = await this.server.simulateTransaction(tx)
|
|
310
|
+
if (rpc.Api.isSimulationError(simulation))
|
|
311
|
+
throw new Error(simulation.error)
|
|
312
|
+
if (rpc.Api.isSimulationRestore(simulation))
|
|
313
|
+
throw new Error('The contract instance or code was archived during the keepalive, retry it to restore them')
|
|
314
|
+
//assembled here, not through the contract client: its signing path declares the resource fee twice
|
|
315
|
+
const prepared = rpc.assembleTransaction(tx, simulation).build()
|
|
316
|
+
if (typeof signTransaction !== 'function')
|
|
317
|
+
throw new Error('No signTransaction callback to sign the keepalive transaction')
|
|
318
|
+
const {signedTxXdr, error} = await signTransaction(prepared.toXDR(), {networkPassphrase, address: this.publicKey})
|
|
319
|
+
if (error)
|
|
320
|
+
throw new Error(`Keepalive transaction was not signed: ${error.message ?? error}`)
|
|
321
|
+
await submitTransaction(this.server, TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase))
|
|
322
|
+
return simulation
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Ledger close time the contract converts lifetimes with
|
|
327
|
+
* @return {Promise<number>} - Seconds per ledger
|
|
328
|
+
* @private
|
|
329
|
+
*/
|
|
330
|
+
async loadLedgerTime() {
|
|
331
|
+
try {
|
|
332
|
+
return Number((await this.loadConfig())?.ledger_time) || DEFAULT_LEDGER_TIME
|
|
333
|
+
} catch (e) {
|
|
334
|
+
return DEFAULT_LEDGER_TIME //the extension itself reports an unreachable or archived contract
|
|
335
|
+
}
|
|
247
336
|
}
|
|
248
337
|
|
|
249
338
|
/**
|
|
@@ -263,19 +352,79 @@ export class AxisContractClient {
|
|
|
263
352
|
* Declare all order ids of a simulated trading call, and the entries the settlement may write for their makers,
|
|
264
353
|
* in the read-write footprint (if enabled), so the transaction survives book changes before it is applied.
|
|
265
354
|
* @param {contract.AssembledTransaction} tx - Simulated transaction
|
|
266
|
-
* @param {string[]}
|
|
355
|
+
* @param {{tokens?: string[], passThrough?: string[], receiver?: string, bought?: string, takerOrder?: bigint}} settlement - Tokens
|
|
356
|
+
* the call trades and how it settles (see `FootprintOptions`)
|
|
267
357
|
* @param {...Array<bigint>} idLists - Order ids passed to the contract call
|
|
268
358
|
* @return {Promise<void>}
|
|
269
359
|
* @private
|
|
270
360
|
*/
|
|
271
|
-
async updateTradeFootprint(tx,
|
|
361
|
+
async updateTradeFootprint(tx, settlement, ...idLists) {
|
|
272
362
|
if (this.autoFootprint) {
|
|
273
363
|
const orderIds = collectOrderIds(...idLists)
|
|
274
|
-
await completeFootprint(tx, this.client.options.contractId, orderIds, {server: this.server,
|
|
364
|
+
await completeFootprint(tx, this.client.options.contractId, orderIds, {...settlement, server: this.server, assetCache: this.assetCache})
|
|
275
365
|
}
|
|
276
366
|
}
|
|
277
367
|
}
|
|
278
368
|
|
|
369
|
+
/**
|
|
370
|
+
* Ledger keys of the contract instance and its Wasm code, and those of them that are archived
|
|
371
|
+
* @param {rpc.Server} server
|
|
372
|
+
* @param {string} contractId
|
|
373
|
+
* @return {Promise<{keys: xdr.LedgerKey[], archived: xdr.LedgerKey[]}>}
|
|
374
|
+
* @internal
|
|
375
|
+
*/
|
|
376
|
+
async function contractLifetimeEntries(server, contractId) {
|
|
377
|
+
const instanceKey = new Contract(contractId).getFootprint()
|
|
378
|
+
const instance = await server.getLedgerEntries(instanceKey)
|
|
379
|
+
const executable = instance.entries[0]?.val?.contractData?.val?.instance?.executable
|
|
380
|
+
if (!executable)
|
|
381
|
+
throw new Error(`Contract ${contractId} instance not found`)
|
|
382
|
+
if (!executable.wasmHash)
|
|
383
|
+
throw new Error(`Contract ${contractId} has no Wasm code`)
|
|
384
|
+
const codeKey = xdr.LedgerKey.contractCode(new xdr.LedgerKeyContractCode({hash: executable.wasmHash}))
|
|
385
|
+
const code = await server.getLedgerEntries(codeKey)
|
|
386
|
+
const archived = []
|
|
387
|
+
if (isArchived(instance.entries[0], instance.latestLedger))
|
|
388
|
+
archived.push(instanceKey)
|
|
389
|
+
//code the RPC does not return is evicted, the restoration brings it back
|
|
390
|
+
if (!code.entries[0] || isArchived(code.entries[0], code.latestLedger))
|
|
391
|
+
archived.push(codeKey)
|
|
392
|
+
return {keys: [instanceKey, codeKey], archived}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Whether a ledger entry is no longer live for the transactions following the latest ledger
|
|
397
|
+
* @param {rpc.Api.LedgerEntryResult} entry
|
|
398
|
+
* @param {number} latestLedger
|
|
399
|
+
* @return {boolean}
|
|
400
|
+
* @internal
|
|
401
|
+
*/
|
|
402
|
+
function isArchived(entry, latestLedger) {
|
|
403
|
+
return entry.liveUntilLedgerSeq !== undefined && entry.liveUntilLedgerSeq <= latestLedger
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Submit a signed transaction and wait for its result
|
|
408
|
+
* @param {rpc.Server} server
|
|
409
|
+
* @param {import('@stellar/stellar-sdk').Transaction} tx
|
|
410
|
+
* @return {Promise<void>}
|
|
411
|
+
* @throws {Error} - If the transaction is rejected, fails or is not included in time
|
|
412
|
+
* @internal
|
|
413
|
+
*/
|
|
414
|
+
async function submitTransaction(server, tx) {
|
|
415
|
+
const sent = await server.sendTransaction(tx)
|
|
416
|
+
if (sent.status !== 'PENDING' && sent.status !== 'DUPLICATE')
|
|
417
|
+
throw new Error(`Transaction ${sent.hash} rejected: ${sent.errorResult?.result?.type ?? sent.status}`)
|
|
418
|
+
const res = await server.pollTransaction(sent.hash, {attempts: TX_TIMEOUT})
|
|
419
|
+
if (res.status === 'FAILED') {
|
|
420
|
+
const error = new Error(`Transaction ${sent.hash} failed: ${res.resultXdr?.result?.type ?? 'unknown result'}`)
|
|
421
|
+
error.hash = sent.hash
|
|
422
|
+
throw error
|
|
423
|
+
}
|
|
424
|
+
if (res.status !== 'SUCCESS')
|
|
425
|
+
throw new Error(`Transaction ${sent.hash} was not included in time`)
|
|
426
|
+
}
|
|
427
|
+
|
|
279
428
|
/**
|
|
280
429
|
* Map the client-side approval to the contract `Approval` argument
|
|
281
430
|
* @param {Approval} [approve]
|
|
@@ -303,6 +452,19 @@ async function signAndSend(tx) {
|
|
|
303
452
|
}
|
|
304
453
|
|
|
305
454
|
async function execTrade(params, direction, context) {
|
|
455
|
+
const result = await signAndSend(await prepareTrade(params, direction, context))
|
|
456
|
+
return [result[0], result[1], result[2] ?? undefined]
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Simulate a trade and complete its footprint
|
|
461
|
+
* @param {BuyTradeArguments|SellTradeArguments} params
|
|
462
|
+
* @param {number} direction
|
|
463
|
+
* @param {AxisContractClient} context
|
|
464
|
+
* @return {Promise<contract.AssembledTransaction>}
|
|
465
|
+
* @internal
|
|
466
|
+
*/
|
|
467
|
+
async function prepareTrade(params, direction, context) {
|
|
306
468
|
//the id of the order created for the remainder derives from the trader and this nonce; generated per call, never supplied by the caller
|
|
307
469
|
const nonce = generateNonce()
|
|
308
470
|
const payload = {
|
|
@@ -322,9 +484,27 @@ async function execTrade(params, direction, context) {
|
|
|
322
484
|
processSimulationErrors(tx)
|
|
323
485
|
//the remainder of a Limit trade becomes an order under an id known in advance - declare it even if the simulation filled the quote
|
|
324
486
|
const remainder = params.kind === OrderKind.Limit ? [orderId(params.trader, nonce)] : []
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
487
|
+
//the bought asset passes through the contract on its way to the trader
|
|
488
|
+
await context.updateTradeFootprint(tx, {
|
|
489
|
+
tokens: [params.selling, params.buying],
|
|
490
|
+
passThrough: [params.buying],
|
|
491
|
+
receiver: params.trader,
|
|
492
|
+
bought: params.buying
|
|
493
|
+
}, payload.orders, remainder)
|
|
494
|
+
return tx
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Fee and expected result of a simulated transaction
|
|
499
|
+
* @param {contract.AssembledTransaction} tx - Simulated transaction with its footprint completed
|
|
500
|
+
* @param {string} inclusionFee - Inclusion fee bid of the client
|
|
501
|
+
* @return {TradeEstimate}
|
|
502
|
+
* @internal
|
|
503
|
+
*/
|
|
504
|
+
function estimateTx(tx, inclusionFee) {
|
|
505
|
+
const fee = BigInt(tx.built.fee)
|
|
506
|
+
const [sold, bought, orderId] = tx.result
|
|
507
|
+
return {fee, inclusionFee: BigInt(inclusionFee), resourceFee: fee - BigInt(inclusionFee), sold, bought, orderId: orderId ?? undefined}
|
|
328
508
|
}
|
|
329
509
|
|
|
330
510
|
/**
|
|
@@ -334,15 +514,15 @@ async function execTrade(params, direction, context) {
|
|
|
334
514
|
* @property {string} rpcUrl - URL of the RPC server
|
|
335
515
|
* @property {string} contractId - DEX contract ID
|
|
336
516
|
* @property {string} [networkPassphrase] - Network passphrase (Pubnet passphrase by default)
|
|
337
|
-
* @property {string} [fee] -
|
|
517
|
+
* @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top
|
|
338
518
|
* @property {boolean} [autoFootprint] - Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default)
|
|
339
519
|
*/
|
|
340
520
|
|
|
341
521
|
/**
|
|
342
|
-
* @callback SignTransactionCallback - Callback for signing transactions generated by the client
|
|
343
|
-
* @param {string}
|
|
344
|
-
* @param {{
|
|
345
|
-
* @return {Promise<{signedTxXdr: string,
|
|
522
|
+
* @callback SignTransactionCallback - Callback for signing transactions generated by the client (`@stellar/stellar-sdk` 17 contract client shape)
|
|
523
|
+
* @param {string} xdr - Transaction XDR to sign
|
|
524
|
+
* @param {{networkPassphrase?: string, address?: string, submit?: boolean, submitUrl?: string}} [opts] - Signing options passed by the SDK
|
|
525
|
+
* @return {Promise<{signedTxXdr: string, signerAddress?: string, error?: *}>} - Signed transaction response
|
|
346
526
|
*/
|
|
347
527
|
|
|
348
528
|
/**
|
|
@@ -379,6 +559,16 @@ async function execTrade(params, direction, context) {
|
|
|
379
559
|
* @property {bigint} price - Price a trader willing to accept, maximum `selling` tokens per 1 `buying`
|
|
380
560
|
*/
|
|
381
561
|
|
|
562
|
+
/**
|
|
563
|
+
* @typedef {{}} TradeEstimate - Simulated trade, nothing signed or submitted
|
|
564
|
+
* @property {bigint} fee - Maximum total network fee of the transaction, in stroops (inclusion fee bid plus resource fee)
|
|
565
|
+
* @property {bigint} inclusionFee - Inclusion fee bid, in stroops (the network charges the market rate up to it)
|
|
566
|
+
* @property {bigint} resourceFee - Resource fee, in stroops, including the rent of an order created for the remainder
|
|
567
|
+
* @property {bigint} sold - Expected amount of sold tokens
|
|
568
|
+
* @property {bigint} bought - Expected amount of bought tokens
|
|
569
|
+
* @property {bigint} [orderId] - ID of the order the remainder would create
|
|
570
|
+
*/
|
|
571
|
+
|
|
382
572
|
/**
|
|
383
573
|
* @typedef {{}} TradeStep - A trade step in a multi-market swap path
|
|
384
574
|
* @property {string} asset - Asset to buy at this step
|
|
@@ -422,7 +612,7 @@ async function execTrade(params, direction, context) {
|
|
|
422
612
|
|
|
423
613
|
/**
|
|
424
614
|
* @typedef {{}} MethodOptions
|
|
425
|
-
* @property {string} [fee] -
|
|
615
|
+
* @property {string} [fee] - Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top
|
|
426
616
|
*/
|
|
427
617
|
|
|
428
618
|
/**
|
|
@@ -433,29 +623,32 @@ async function execTrade(params, direction, context) {
|
|
|
433
623
|
* @property {string} buying - Buying token address
|
|
434
624
|
* @property {bigint} amount - Amount left to sell
|
|
435
625
|
* @property {bigint} price - Order price (`buying` per 1 `selling`, 18 decimals)
|
|
436
|
-
* @property {bigint} expires - Expiration timestamp (0 = no expiration)
|
|
626
|
+
* @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
|
|
437
627
|
*/
|
|
438
628
|
|
|
439
629
|
/**
|
|
440
630
|
* @typedef {{}} Config - Contract configuration
|
|
631
|
+
* @property {string} safety_admin - Address of the account allowed to freeze the contract and change the configuration
|
|
441
632
|
* @property {string} oracle - Oracle contract address
|
|
442
|
-
* @property {
|
|
443
|
-
* @property {
|
|
633
|
+
* @property {number} listing_min_days - Days of price feeds a new market must buy (0 opens markets without a fee)
|
|
634
|
+
* @property {bigint} market_listing_fee - Amount of oracle fee tokens paid by the market creator to provision the oracle price feeds
|
|
635
|
+
* (the oracle daily fee x `listing_min_days`)
|
|
444
636
|
* @property {bigint} min_trade_size - Minimum trade value in USD, with 7 decimals precision (0 disables the limit)
|
|
637
|
+
* @property {number} ledger_time - Expected average ledger close time in seconds, used to convert entry lifetimes into ledgers
|
|
445
638
|
*/
|
|
446
639
|
|
|
447
640
|
/**
|
|
448
641
|
* @typedef {{}} MarketSide - Market asset descriptor
|
|
449
642
|
* @property {string} asset - Token contract address
|
|
450
|
-
* @property {boolean} listed - Whether the asset is quoted by the oracle
|
|
643
|
+
* @property {boolean} listed - Whether the asset is quoted by the oracle (with token decimals the valuation can handle)
|
|
451
644
|
* @property {number} decimals - Token decimals (fetched only for listed assets)
|
|
452
645
|
*/
|
|
453
646
|
|
|
454
647
|
/**
|
|
455
648
|
* @typedef {{}} Market - Market record, stored on-chain
|
|
456
|
-
* @property {MarketSide}
|
|
457
|
-
* @property {MarketSide}
|
|
458
|
-
* @property {bigint} created - Creation timestamp
|
|
649
|
+
* @property {MarketSide} base - Base asset, the first of the pair in canonical order
|
|
650
|
+
* @property {MarketSide} quote - Quote asset, the second of the pair in canonical order
|
|
651
|
+
* @property {bigint} created - Creation UNIX timestamp in seconds
|
|
459
652
|
*/
|
|
460
653
|
|
|
461
654
|
/**
|
|
@@ -487,7 +680,7 @@ async function execTrade(params, direction, context) {
|
|
|
487
680
|
* @property {string} owner - Maker address
|
|
488
681
|
* @property {bigint} price - Order price
|
|
489
682
|
* @property {bigint} amount - Current amount
|
|
490
|
-
* @property {bigint} expires - Expiration timestamp (0 = no expiration)
|
|
683
|
+
* @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
|
|
491
684
|
*/
|
|
492
685
|
|
|
493
686
|
/**
|
|
@@ -495,20 +688,21 @@ async function execTrade(params, direction, context) {
|
|
|
495
688
|
* @property {bigint} id - Unique order identifier
|
|
496
689
|
* @property {bigint} price - Order price
|
|
497
690
|
* @property {bigint} amount - Current amount (0 = removed)
|
|
498
|
-
* @property {bigint} expires - Expiration timestamp (0 = no expiration)
|
|
691
|
+
* @property {bigint} expires - Expiration UNIX timestamp in seconds (0 = no expiration)
|
|
499
692
|
*/
|
|
500
693
|
|
|
501
694
|
/**
|
|
502
|
-
* @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle
|
|
503
|
-
*
|
|
695
|
+
* @typedef {object} OrderSkippedContractEvent - Orderbook `skip` event, a listed order its maker could not settle: backing
|
|
696
|
+
* short of the fill, a missing or deauthorized trustline for the taker's asset, or the maker's asset could not be collected.
|
|
697
|
+
* The order is left unchanged. For `crossfill` it also flags a taker order its owner cannot back or be paid for
|
|
504
698
|
* @property {bigint} order - Order id
|
|
505
699
|
*/
|
|
506
700
|
|
|
507
701
|
/**
|
|
508
702
|
* @typedef {object} MarketRefreshContractEvent - Orderbook `refresh` event, a market checked against the oracle
|
|
509
|
-
* (topics: `refresh`, `
|
|
510
|
-
* @property {string}
|
|
511
|
-
* @property {string}
|
|
703
|
+
* (topics: `refresh`, `base`, `quote`, no data)
|
|
704
|
+
* @property {string} base - Base market asset (canonical order, topic)
|
|
705
|
+
* @property {string} quote - Quote market asset (canonical order, topic)
|
|
512
706
|
*/
|
|
513
707
|
|
|
514
708
|
/**
|
|
@@ -517,6 +711,7 @@ async function execTrade(params, direction, context) {
|
|
|
517
711
|
*/
|
|
518
712
|
|
|
519
713
|
/**
|
|
520
|
-
* @typedef {object} ConfigChangedContractEvent - `config` update notification event
|
|
714
|
+
* @typedef {object} ConfigChangedContractEvent - `config` update notification event (constructor, `delegate`, `set_oracle`,
|
|
715
|
+
* `set_floor`, `set_listing_min_days`, `set_ledger_time`)
|
|
521
716
|
* @property {Config} config - Contract configuration after the call
|
|
522
717
|
*/
|
package/src/order-id.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
import {xdr, Address, hash} from '@stellar/stellar-sdk'
|
|
2
|
-
|
|
3
|
-
const U64_MAX = (1n << 64n) - 1n
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Compute the id of the order `owner` creates with `nonce`.
|
|
7
|
-
* Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`
|
|
8
|
-
* interpreted as a big-endian `u128` (the full 128 bits, no mask).
|
|
9
|
-
* @param {string} owner - Order owner address (account or contract)
|
|
10
|
-
* @param {bigint|number|string} nonce - Client-chosen u64 nonce
|
|
11
|
-
* @return {bigint} - u128 order id
|
|
12
|
-
*/
|
|
13
|
-
export function orderId(owner, nonce) {
|
|
14
|
-
nonce = BigInt(nonce)
|
|
15
|
-
if (nonce < 0n || nonce > U64_MAX)
|
|
16
|
-
throw new RangeError('Nonce must fit u64')
|
|
17
|
-
const payload = xdr.ScVal.scvVec([
|
|
18
|
-
Address.fromString(owner).toScVal(),
|
|
19
|
-
xdr.ScVal.scvU64(nonce)
|
|
20
|
-
]).toXDR()
|
|
21
|
-
const digest = hash(payload)
|
|
22
|
-
let id = 0n
|
|
23
|
-
for (let i = 0; i < 16; i++) {
|
|
24
|
-
id = (id << 8n) | BigInt(digest[i])
|
|
25
|
-
}
|
|
26
|
-
return id
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Generate a u64 order nonce: wall clock (in milliseconds) shifted left by 22 bits plus 22 random bits.
|
|
31
|
-
* The clock part fits 42 bits until the year 2109, so the nonce never overflows u64; the random part makes
|
|
32
|
-
* collisions among the orders an account creates within the same millisecond negligible.
|
|
33
|
-
* Internal to the client - consumers never supply or observe nonces, `buy`/`sell` generate one per call.
|
|
34
|
-
* @return {bigint}
|
|
35
|
-
* @internal
|
|
36
|
-
*/
|
|
37
|
-
export function generateNonce() {
|
|
38
|
-
return (BigInt(Date.now()) << 22n) | BigInt(randomBits22())
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function randomBits22() {
|
|
42
|
-
const crypto = globalThis.crypto
|
|
43
|
-
if (crypto?.getRandomValues) {
|
|
44
|
-
return crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff
|
|
45
|
-
}
|
|
46
|
-
return Math.floor(Math.random() * 0x400000)
|
|
47
|
-
}
|
|
1
|
+
import {xdr, Address, hash} from '@stellar/stellar-sdk'
|
|
2
|
+
|
|
3
|
+
const U64_MAX = (1n << 64n) - 1n
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Compute the id of the order `owner` creates with `nonce`.
|
|
7
|
+
* Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`
|
|
8
|
+
* interpreted as a big-endian `u128` (the full 128 bits, no mask).
|
|
9
|
+
* @param {string} owner - Order owner address (account or contract)
|
|
10
|
+
* @param {bigint|number|string} nonce - Client-chosen u64 nonce
|
|
11
|
+
* @return {bigint} - u128 order id
|
|
12
|
+
*/
|
|
13
|
+
export function orderId(owner, nonce) {
|
|
14
|
+
nonce = BigInt(nonce)
|
|
15
|
+
if (nonce < 0n || nonce > U64_MAX)
|
|
16
|
+
throw new RangeError('Nonce must fit u64')
|
|
17
|
+
const payload = xdr.ScVal.scvVec([
|
|
18
|
+
Address.fromString(owner).toScVal(),
|
|
19
|
+
xdr.ScVal.scvU64(nonce)
|
|
20
|
+
]).toXDR()
|
|
21
|
+
const digest = hash(payload)
|
|
22
|
+
let id = 0n
|
|
23
|
+
for (let i = 0; i < 16; i++) {
|
|
24
|
+
id = (id << 8n) | BigInt(digest[i])
|
|
25
|
+
}
|
|
26
|
+
return id
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Generate a u64 order nonce: wall clock (in milliseconds) shifted left by 22 bits plus 22 random bits.
|
|
31
|
+
* The clock part fits 42 bits until the year 2109, so the nonce never overflows u64; the random part makes
|
|
32
|
+
* collisions among the orders an account creates within the same millisecond negligible.
|
|
33
|
+
* Internal to the client - consumers never supply or observe nonces, `buy`/`sell` generate one per call.
|
|
34
|
+
* @return {bigint}
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
export function generateNonce() {
|
|
38
|
+
return (BigInt(Date.now()) << 22n) | BigInt(randomBits22())
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function randomBits22() {
|
|
42
|
+
const crypto = globalThis.crypto
|
|
43
|
+
if (crypto?.getRandomValues) {
|
|
44
|
+
return crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff
|
|
45
|
+
}
|
|
46
|
+
return Math.floor(Math.random() * 0x400000)
|
|
47
|
+
}
|
package/src/stream-client.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {Emitter} from './emitter.js'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* WebSocket client of the
|
|
4
|
+
* WebSocket client of the AXIS API push channel
|
|
5
5
|
*
|
|
6
6
|
* Emits `open`, `close` and `error` (server errors not tied to a subscription).
|
|
7
7
|
*/
|
|
8
8
|
export class AxisStreamClient extends Emitter {
|
|
9
9
|
/**
|
|
10
|
-
* @param {string} url - WebSocket endpoint, e.g. `wss://api.axis.markets/ws`
|
|
10
|
+
* @param {string} url - WebSocket endpoint, e.g. `wss://demo-api.axis.markets/ws` (testnet)
|
|
11
11
|
* @param {StreamClientOptions} [options]
|
|
12
12
|
*/
|
|
13
13
|
constructor(url, {WebSocket: WebSocketImpl, pingInterval = 20_000, minReconnectDelay = 1_000, maxReconnectDelay = 30_000} = {}) {
|