@axis-markets/client 0.9.0 → 0.9.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axis-markets/client",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "AXIS contract and API client",
5
5
  "author": "team@stellar.expert",
6
6
  "license": "MIT",
package/src/api-client.js CHANGED
@@ -248,9 +248,11 @@ export class AxisApiClient {
248
248
  * @typedef {{}} QuotePathStep
249
249
  * @property {string} selling - Selling asset contract id at this hop
250
250
  * @property {string} buying - Buying asset contract id at this hop
251
- * @property {string[]} orders - Maker order IDs matched at this hop
252
- * @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):
253
- * a trade limit at this price crosses every listed order
251
+ * @property {string[]} orders - Maker order IDs to pass to the contract: the orders the quote fills, followed on a
252
+ * direct route by spare orders the contract reaches only when it passes over one of them (at most 19 in all)
253
+ * @property {string} [worstPrice] - Highest price among the orders the quote fills (maker `buying` per `selling`, 18
254
+ * decimals): a trade limit at this price crosses them all. Spares are priced at or below it, except in a `maxPrice`
255
+ * crossing, where they reach up to `maxPrice`
254
256
  */
255
257
 
256
258
  /**
@@ -325,9 +327,22 @@ export class AxisApiClient {
325
327
  /**
326
328
  * @typedef {{}} ContractInfo - Contract state tracked by the indexer
327
329
  * @property {string} address - AXIS contract address
330
+ * @property {'mainnet'|'testnet'} [network] - Stellar network of the contract
328
331
  * @property {boolean} frozen - Whether trading is blocked by the safety admin
329
332
  * @property {ContractInfoConfig} [config] - Contract configuration
330
333
  * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
334
+ * @property {ContractInfoAsset[]} [assets] - Metadata of the market tokens
335
+ */
336
+
337
+ /**
338
+ * @typedef {{}} ContractInfoAsset - Market token metadata (only `contract` until the AXIS API resolves it)
339
+ * @property {string} contract - Token contract address
340
+ * @property {string} [code] - Asset code (token symbol)
341
+ * @property {string} [issuer] - Issuer account of a classic asset, `native` for XLM, absent for a SEP-41 token
342
+ * @property {number} [decimals] - Token decimals
343
+ * @property {string} [name] - Asset name
344
+ * @property {string} [domain] - Home domain of the issuer
345
+ * @property {string} [icon] - Icon URL
331
346
  */
332
347
 
333
348
  /**
package/src/errors.js CHANGED
@@ -43,14 +43,39 @@ export const TokenErrors = {
43
43
  13: {message: "TrustlineMissingError"}
44
44
  }
45
45
 
46
+ /**
47
+ * Token functions whose failure is a failed transfer, which either side may have caused
48
+ */
49
+ const TRANSFER_FUNCTIONS = new Set(['transfer', 'transfer_from'])
50
+
51
+ /**
52
+ * Diagnostic `error` event of a contract error
53
+ * @typedef {object} ErrorEvent
54
+ * @property {number} code - Contract error code
55
+ * @property {string} [contract] - Contract that emitted the event, absent for the host outside any contract
56
+ * @property {string} [fn] - Function of the contract whose call failed, on the event its caller emits for the failure
57
+ * @property {boolean} [caught] - The caller caught that failure (`try_call`)
58
+ * @private
59
+ */
60
+
61
+ /**
62
+ * Contract call an error failed on its way up
63
+ * @typedef {object} ErrorFrame
64
+ * @property {string} [contract] - Contract address, when the event log names it
65
+ * @property {string} [fn] - Function its caller called it with, absent for the invoked contract itself
66
+ * @private
67
+ */
68
+
46
69
  /**
47
70
  * Handle simulation errors if any. A contract error raised by the DEX contract is mapped by its code. An error raised by
48
- * another contract the call invoked (the token whose transfer failed) is reported with `tokenError` set: a failed
49
- * payment to a maker fails the whole call with the token's own error, and the contract does not tell whether the payer
50
- * could not pay or the maker could not be credited (e.g. a full trustline), so neither side is assumed
71
+ * a token transfer the call made is reported with `tokenError` set: a failed payment to a maker fails the whole call
72
+ * with the token's own error, and the contract does not tell whether the payer could not pay or the maker could not be
73
+ * credited (e.g. a full trustline), so neither side is assumed. An error raised by any other contract (the oracle, a
74
+ * token burn) is reported with the `contract` and the `fn` it failed in
51
75
  * @param {contract.AssembledTransaction} tx
52
- * @throws {Error} - Error with numeric `code` property for known contract errors, plus `tokenError` and `contract`
53
- * for errors raised by a token
76
+ * @throws {Error} - Error with numeric `code` property for known contract errors, plus `contract` and `fn` for errors
77
+ * raised by another contract, and `tokenError` for a failed token transfer; any other failure as an Error with the
78
+ * raw simulation error in `details`
54
79
  * @internal
55
80
  */
56
81
  export function processSimulationErrors(tx) {
@@ -59,61 +84,123 @@ export function processSimulationErrors(tx) {
59
84
  const contractErrorMatch = /HostError: Error\(Contract, #(\d+)\)/.exec(message)
60
85
  if (contractErrorMatch) {
61
86
  const code = parseInt(contractErrorMatch[1], 10)
62
- const error = contractError(code, findErrorSource(message, code)?.contract, tx.options?.contractId)
87
+ //RPC servers return the event log in `events`, older ones appended it to the error message
88
+ let events = diagnosticErrorEvents(tx.simulation.events ?? [])
89
+ if (!events.length) {
90
+ events = parseErrorEvents(message)
91
+ }
92
+ const error = contractError(code, findErrorChain(events, code), tx.options?.contractId)
63
93
  if (error)
64
94
  throw error
65
95
  }
66
- throw message
96
+ throw simulationError(message)
67
97
  }
68
98
  }
69
99
 
70
100
  /**
71
- * Wrapped aggregated error - token error when another contract than the DEX raised it, a DEX contract error otherwise
101
+ * Simulation failure without a known contract error (a host or authorization error, an unknown contract code)
102
+ * @param {string} message - Raw simulation error, followed by its diagnostic event log
103
+ * @return {Error} - Error named after the first line of the raw error, which it keeps in `details`
104
+ * @private
105
+ */
106
+ function simulationError(message) {
107
+ const error = new Error(`Simulation failed: ${String(message).split('\n', 1)[0].trim()}`)
108
+ error.details = message
109
+ return error
110
+ }
111
+
112
+ /**
113
+ * Wrapped aggregated error: a DEX contract error when the DEX raised it, a token error when a token transfer the DEX
114
+ * made failed (in the token or in a contract the token called), an error of another contract otherwise
72
115
  * @param {number} code - Contract error code
73
- * @param {string} [source] - Contract that raised the error, when known
116
+ * @param {ErrorFrame[]} chain - Calls the error failed, from the invoked contract down to the one that raised it
74
117
  * @param {string} [dexContract] - DEX contract address, when known
75
- * @return {Error|null} - Null for an unknown code of the DEX
118
+ * @return {Error|null} - Null for an unknown code of the DEX, or an error of another contract the log does not name
76
119
  * @private
77
120
  */
78
- function contractError(code, source, dexContract) {
79
- const raisedByToken = source && dexContract ? source !== dexContract : !ContractErrors[code] && !!TokenErrors[code]
80
- if (raisedByToken)
81
- return tokenError(code, source)
82
- const err = ContractErrors[code]
83
- if (!err)
121
+ function contractError(code, chain, dexContract) {
122
+ const {contract, fn} = chain[chain.length - 1]
123
+ //only the invoked contract runs without a caller: contracts cannot be re-entered
124
+ const raisedByDex = contract && dexContract ? contract === dexContract : !fn
125
+ if (raisedByDex) {
126
+ const err = ContractErrors[code]
127
+ if (!err)
128
+ return null
129
+ const error = new Error(`Contract execution error: #${code} ${err.message}`)
130
+ error.code = code
131
+ return error
132
+ }
133
+ //the call the DEX made tells a settlement transfer, whatever the token called in turn
134
+ const dexFrame = dexContract ? chain.findIndex(frame => frame.contract === dexContract) : -1
135
+ const call = chain[Math.max(dexFrame, 0) + 1]
136
+ if (TRANSFER_FUNCTIONS.has(call?.fn))
137
+ return tokenError(code, call.contract, call.fn)
138
+ if (!contract)
84
139
  return null
85
- const error = new Error(`Contract execution error: #${code} ${err.message}`)
140
+ const error = new Error(`Contract ${contract} failed${fn ? ` in ${fn}` : ''}: #${code}`)
86
141
  error.code = code
142
+ error.contract = contract
143
+ if (fn) {
144
+ error.fn = fn
145
+ }
87
146
  return error
88
147
  }
89
148
 
90
149
  /**
91
- * Locate the contract that raised the error in a simulation event log. The log lists events newest first and an error
92
- * is re-emitted by every frame it fails, so the oldest `error` event with the code is where it was raised (errors of
93
- * caught calls carry other codes)
94
- * @param {string} message - Simulation error with its diagnostic event log
95
- * @param {number} code - Error code the simulation failed with
96
- * @return {{contract: string}|null}
150
+ * Calls the error failed on its way up. Every frame the error fails re-emits it, and a failed contract call makes the
151
+ * caller emit an event naming the function it called, which starts the frame of the contract that emitted the older
152
+ * events. The last frame raised the error. A failure its caller caught (`try_call`), or an older event of another
153
+ * contract with no failed call between, ends the chain: errors of caught calls normally carry other codes
154
+ * @param {ErrorEvent[]} events - Error events, newest first
155
+ * @param {number} code - Error code the call failed with
156
+ * @return {ErrorFrame[]} - From the invoked contract down, never empty
97
157
  * @private
98
158
  */
99
- function findErrorSource(message, code) {
100
- let source = null
101
- for (const match of message.matchAll(/contract:(C[A-Z2-7]{55}),\s*topics:\[error, Error\(Contract, #(\d+)\)/g)) {
102
- if (parseInt(match[2], 10) === code) {
103
- source = {contract: match[1]}
159
+ function findErrorChain(events, code) {
160
+ const chain = [{}]
161
+ for (const event of events) {
162
+ if (event.code !== code)
163
+ continue
164
+ if (event.caught)
165
+ break
166
+ const frame = chain[chain.length - 1]
167
+ if (frame.contract && event.contract && event.contract !== frame.contract)
168
+ break
169
+ frame.contract ??= event.contract
170
+ if (event.fn) {
171
+ chain.push({fn: event.fn})
104
172
  }
105
173
  }
106
- return source
174
+ return chain
175
+ }
176
+
177
+ /**
178
+ * Contract error events of a simulation error message with the event log appended
179
+ * @param {string} message - Simulation error with its diagnostic event log (newest first)
180
+ * @return {ErrorEvent[]} - Newest first
181
+ * @private
182
+ */
183
+ function parseErrorEvents(message) {
184
+ const events = []
185
+ for (const line of message.split('\n')) {
186
+ const match = /\[[^\]]*Event[^\]]*\]\s*(?:contract:(C[A-Z2-7]{55}),\s*)?topics:\[error, Error\(Contract, #(\d+)\)\](?:,\s*data:(.*))?/.exec(line)
187
+ if (!match)
188
+ continue
189
+ const call = /^\["contract (try_)?call failed", (\w+)/.exec(match[3] ?? '')
190
+ events.push({code: parseInt(match[2], 10), contract: match[1], fn: call?.[2], caught: !!call?.[1]})
191
+ }
192
+ return events
107
193
  }
108
194
 
109
195
  /**
110
196
  * Error raised by a token transfer during settlement
111
- * @param {number} code - Token error code
197
+ * @param {number} code - Error code of the token, or of a contract its transfer called
112
198
  * @param {string} [contract] - Token contract address, when the event log names it
199
+ * @param {string} fn - Transfer function that failed
113
200
  * @return {Error}
114
201
  * @private
115
202
  */
116
- function tokenError(code, contract) {
203
+ function tokenError(code, contract, fn) {
117
204
  const name = TokenErrors[code]?.message || 'token error'
118
205
  const error = new Error(`Token transfer failed: #${code} ${name}${contract ? ` (token ${contract})` : ''}. ` +
119
206
  `Either side of the transfer may be at fault: the payer's balance or allowance, or the recipient's trustline ` +
@@ -123,6 +210,7 @@ function tokenError(code, contract) {
123
210
  if (contract) {
124
211
  error.contract = contract
125
212
  }
213
+ error.fn = fn
126
214
  return error
127
215
  }
128
216
 
@@ -135,15 +223,16 @@ function tokenError(code, contract) {
135
223
  * Transaction hash, its result (or its result code, when known without the result), the diagnostic events of a failed
136
224
  * call and the DEX contract address
137
225
  * @return {Error} - Error with `status`, `hash`, `result` (Horizon-style transaction result code, e.g. `tx_bad_seq`),
138
- * `opResult` (operation result code of `tx_failed`, e.g. `invoke_host_function_trapped`), and `code` (plus `tokenError`
139
- * and `contract` for a token) when the diagnostic events name the contract error the call failed with
226
+ * `opResult` (operation result code of `tx_failed`, e.g. `invoke_host_function_trapped`), and `code` (plus `contract`
227
+ * and `fn` for another contract, and `tokenError` for a token transfer) when the diagnostic events name the contract
228
+ * error the call failed with
140
229
  * @internal
141
230
  */
142
231
  export function transactionError(status, {hash, result, resultCode: knownCode, events, contractId} = {}) {
143
232
  const resultCode = knownCode ?? (result?.result?.type ? snakeCase(result.result.type) : undefined)
144
233
  const opResult = operationResultCode(result)
145
234
  const cause = events?.length ? findEventError(events) : undefined
146
- const causeError = cause ? contractError(cause.code, cause.contract, contractId) : null
235
+ const causeError = cause ? contractError(cause.code, cause.chain, contractId) : null
147
236
  let message
148
237
  switch (status) {
149
238
  case 'ERROR':
@@ -171,11 +260,9 @@ export function transactionError(status, {hash, result, resultCode: knownCode, e
171
260
  error.opResult = opResult
172
261
  }
173
262
  if (causeError) {
174
- error.code = causeError.code
175
- if (causeError.tokenError) {
176
- error.tokenError = true
177
- if (causeError.contract) {
178
- error.contract = causeError.contract
263
+ for (const key of ['code', 'tokenError', 'contract', 'fn']) {
264
+ if (causeError[key] !== undefined) {
265
+ error[key] = causeError[key]
179
266
  }
180
267
  }
181
268
  }
@@ -202,34 +289,45 @@ function operationResultCode(result) {
202
289
 
203
290
  /**
204
291
  * Contract error a failed call raised, from its diagnostic events (oldest first). An error is re-emitted by every frame
205
- * it fails, so the last error event carries the code the call failed with and the oldest event with that code names the
206
- * contract that raised it
292
+ * it fails, so the last error event carries the code the call failed with
207
293
  * @param {xdr.DiagnosticEvent[]} events
208
- * @return {{code: number, contract?: string}|undefined}
294
+ * @return {{code: number, chain: ErrorFrame[]}|undefined}
209
295
  * @private
210
296
  */
211
297
  function findEventError(events) {
298
+ const errors = diagnosticErrorEvents(events)
299
+ if (!errors.length)
300
+ return undefined
301
+ const {code} = errors[0]
302
+ return {code, chain: findErrorChain(errors, code)}
303
+ }
304
+
305
+ /**
306
+ * Contract error events among diagnostic events
307
+ * @param {xdr.DiagnosticEvent[]} events - Oldest first
308
+ * @return {ErrorEvent[]} - Newest first
309
+ * @private
310
+ */
311
+ function diagnosticErrorEvents(events) {
212
312
  const errors = []
213
313
  for (const event of events) {
214
- const code = eventErrorCode(event)
215
- if (code !== undefined) {
216
- errors.push({code, contract: eventContract(event)})
314
+ const error = errorEvent(event)
315
+ if (error) {
316
+ errors.unshift(error)
217
317
  }
218
318
  }
219
- if (!errors.length)
220
- return undefined
221
- const {code} = errors[errors.length - 1]
222
- return {code, contract: errors.find(error => error.code === code && error.contract)?.contract}
319
+ return errors
223
320
  }
224
321
 
225
322
  /**
226
- * Contract error code of an `error` diagnostic event
323
+ * Contract error of an `error` diagnostic event
227
324
  * @param {xdr.DiagnosticEvent} event
228
- * @return {number|undefined}
325
+ * @return {ErrorEvent|undefined}
229
326
  * @private
230
327
  */
231
- function eventErrorCode(event) {
232
- const topics = event?.event?.body?.value?.topics
328
+ function errorEvent(event) {
329
+ const body = event?.event?.body?.value
330
+ const topics = body?.topics
233
331
  if (!topics || topics.length < 2)
234
332
  return undefined
235
333
  const [name, value] = topics
@@ -237,7 +335,15 @@ function eventErrorCode(event) {
237
335
  return undefined
238
336
  if (value.type !== 'scvError' || value.error.type !== 'sceContract')
239
337
  return undefined
240
- return value.error.contractCode
338
+ const error = {code: value.error.contractCode, contract: eventContract(event)}
339
+ //the caller of a failed contract call reports it as ["contract call failed", fn, args]
340
+ const [message, fn] = body.data?.type === 'scvVec' ? body.data.vec ?? [] : []
341
+ const call = message?.type === 'scvString' && /^contract (try_)?call failed$/.exec(message.str.toString())
342
+ if (call && fn?.type === 'scvSymbol') {
343
+ error.fn = fn.sym.toString()
344
+ error.caught = !!call[1]
345
+ }
346
+ return error
241
347
  }
242
348
 
243
349
  /**
package/src/index.d.ts CHANGED
@@ -470,7 +470,7 @@ export declare class AxisContractClient {
470
470
  /**
471
471
  * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived
472
472
  * ones first with a `RestoreFootprint` transaction.
473
- * @param days - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)
473
+ * @param days - Lifetime in days, 30 by default, at most 179 (the network rejects an extension to its full maximum, 180 days on mainnet)
474
474
  * @returns Ledger sequence both entries live at least until
475
475
  * @throws If `days` is invalid, if the instance is not found, if a simulation or a transaction fails
476
476
  */
@@ -533,9 +533,9 @@ export interface QuotePathStep {
533
533
  selling: string;
534
534
  /** Buying asset contract id at this hop */
535
535
  buying: string;
536
- /** Maker order IDs matched at this hop */
536
+ /** Maker order IDs to pass to the contract: the orders the quote fills, followed on a direct route by spare orders the contract reaches only when it passes over one of them (at most 19 in all) */
537
537
  orders: string[];
538
- /** Highest price among the matched orders (maker `buying` per `selling`, 18 decimals): a trade limit at this price crosses every listed order */
538
+ /** Highest price among the orders the quote fills (maker `buying` per `selling`, 18 decimals): a trade limit at this price crosses them all. Spares are priced at or below it, except in a `maxPrice` crossing, where they reach up to `maxPrice` */
539
539
  worstPrice?: string;
540
540
  }
541
541
 
@@ -687,16 +687,38 @@ export interface ContractInfoMarket {
687
687
  refreshed: string;
688
688
  }
689
689
 
690
+ /** Market token metadata (only `contract` until the AXIS API resolves it) */
691
+ export interface ContractInfoAsset {
692
+ /** Token contract address */
693
+ contract: string;
694
+ /** Asset code (token symbol) */
695
+ code?: string;
696
+ /** Issuer account of a classic asset, `native` for XLM, absent for a SEP-41 token */
697
+ issuer?: string;
698
+ /** Token decimals */
699
+ decimals?: number;
700
+ /** Asset name */
701
+ name?: string;
702
+ /** Home domain of the issuer */
703
+ domain?: string;
704
+ /** Icon URL */
705
+ icon?: string;
706
+ }
707
+
690
708
  /** Contract state tracked by the indexer */
691
709
  export interface ContractInfo {
692
710
  /** AXIS contract address */
693
711
  address: string;
712
+ /** Stellar network of the contract */
713
+ network?: 'mainnet' | 'testnet';
694
714
  /** Whether trading is blocked by the safety admin */
695
715
  frozen: boolean;
696
716
  /** Contract configuration */
697
717
  config?: ContractInfoConfig;
698
718
  /** Markets opened by `subsidize` */
699
719
  markets: ContractInfoMarket[];
720
+ /** Metadata of the market tokens */
721
+ assets?: ContractInfoAsset[];
700
722
  }
701
723
 
702
724
  export interface OrdersParams {
package/src/index.js CHANGED
@@ -291,7 +291,7 @@ export class AxisContractClient {
291
291
  /**
292
292
  * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived
293
293
  * ones first with a `RestoreFootprint` transaction.
294
- * @param {number} [days] - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)
294
+ * @param {number} [days] - Lifetime in days, 30 by default, max 179
295
295
  * @return {Promise<number>} - Ledger sequence both entries live at least until
296
296
  * @throws {Error} - If `days` is invalid, if the instance is not found, if a simulation or a transaction fails
297
297
  */