@axis-markets/client 0.9.1 → 0.9.3

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.1",
3
+ "version": "0.9.3",
4
4
  "description": "AXIS contract and API client",
5
5
  "author": "team@stellar.expert",
6
6
  "license": "MIT",
@@ -117,13 +117,16 @@ export class AxisMarket {
117
117
  * Returns a snapshot, then updates on book changes
118
118
  * @param {{base?: string, depth?: number, step?: string, limit?: number}} params
119
119
  * @param {function(OrderbookDepth): void} callback
120
+ * @param {function(Error): void} [onError] - Called if the API refuses the subscription (see {@link refused})
120
121
  * @return {function(): void} - Unsubscribe function
121
122
  */
122
- subscribeDepth({base = this.base, depth, step, limit} = {}, callback) {
123
+ subscribeDepth({base = this.base, depth, step, limit} = {}, callback, onError) {
123
124
  const market = base + '/' + this.counter(base)
124
125
  return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {
125
126
  if (message.type === 'depth') {
126
127
  callback(message.data)
128
+ } else {
129
+ refused(message, onError)
127
130
  }
128
131
  })
129
132
  }
@@ -132,14 +135,17 @@ export class AxisMarket {
132
135
  * Stream the market trades
133
136
  * Returns a snapshot, then updates on trades
134
137
  * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot
138
+ * @param {function(Error): void} [onError] - Called if the API refuses the subscription (see {@link refused})
135
139
  * @return {function(): void} - Unsubscribe function
136
140
  */
137
- subscribeTrades(callback) {
141
+ subscribeTrades(callback, onError) {
138
142
  return this.axis.stream.subscribe('trades', {market: this.key}, message => {
139
143
  if (message.type === 'trades') {
140
144
  callback(message.trades, true)
141
145
  } else if (message.type === 'trade') {
142
146
  callback([message.trade], false)
147
+ } else {
148
+ refused(message, onError)
143
149
  }
144
150
  })
145
151
  }
@@ -149,15 +155,18 @@ export class AxisMarket {
149
155
  * Returns a snapshot, then updates on trades
150
156
  * @param {{base?: string, resolution: number|string, limit?: number}} params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)
151
157
  * @param {function(Candle[], boolean): void} callback - Candles
158
+ * @param {function(Error): void} [onError] - Called if the API refuses the subscription (see {@link refused})
152
159
  * @return {function(): void} - Unsubscribe function
153
160
  */
154
- subscribeCandles({base = this.base, resolution, limit}, callback) {
161
+ subscribeCandles({base = this.base, resolution, limit}, callback, onError) {
155
162
  const market = base + '/' + this.counter(base)
156
163
  return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {
157
164
  if (message.type === 'candles') {
158
165
  callback(message.candles, true)
159
166
  } else if (message.type === 'candle') {
160
167
  callback([message.candle], false)
168
+ } else {
169
+ refused(message, onError)
161
170
  }
162
171
  })
163
172
  }
@@ -175,6 +184,17 @@ export class AxisMarket {
175
184
  }
176
185
  }
177
186
 
187
+ /**
188
+ * Report a subscription the API refused. The stream drops a refused subscription, the caller subscribes again to retry.
189
+ * @param {StreamMessage} message
190
+ * @param {function(Error): void} [onError]
191
+ */
192
+ function refused(message, onError) {
193
+ if (message.type === 'error') {
194
+ onError?.(new Error(message.error))
195
+ }
196
+ }
197
+
178
198
  /**
179
199
  * @typedef {{}} Signer - Account signing contract calls
180
200
  * @property {string} publicKey - Transaction source account
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
  */
@@ -1405,24 +1405,27 @@ export declare class AxisMarket {
1405
1405
  /**
1406
1406
  * Stream the orderbook depth
1407
1407
  * Returns a snapshot, then updates on book changes
1408
+ * @param onError - Called if the API refuses the subscription, which is then dropped (subscribe again to retry)
1408
1409
  * @returns Unsubscribe function
1409
1410
  */
1410
- subscribeDepth(params: {base?: string, depth?: number, step?: string, limit?: number}, callback: (depth: OrderbookDepth) => void): () => void;
1411
+ subscribeDepth(params: {base?: string, depth?: number, step?: string, limit?: number}, callback: (depth: OrderbookDepth) => void, onError?: (error: Error) => void): () => void;
1411
1412
  /**
1412
1413
  * Stream the market trades
1413
1414
  * Returns a snapshot, then updates on trades
1414
1415
  * @param callback - Trades and whether they are the snapshot
1416
+ * @param onError - Called if the API refuses the subscription, which is then dropped (subscribe again to retry)
1415
1417
  * @returns Unsubscribe function
1416
1418
  */
1417
- subscribeTrades(callback: (trades: ApiTrade[], snapshot: boolean) => void): () => void;
1419
+ subscribeTrades(callback: (trades: ApiTrade[], snapshot: boolean) => void, onError?: (error: Error) => void): () => void;
1418
1420
  /**
1419
1421
  * Stream the market candles
1420
1422
  * Returns a snapshot, then updates on trades
1421
1423
  * @param params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)
1422
1424
  * @param callback - Candles
1425
+ * @param onError - Called if the API refuses the subscription, which is then dropped (subscribe again to retry)
1423
1426
  * @returns Unsubscribe function
1424
1427
  */
1425
- subscribeCandles(params: {base?: string, resolution: number | string, limit?: number}, callback: (candles: Candle[], snapshot: boolean) => void): () => void;
1428
+ subscribeCandles(params: {base?: string, resolution: number | string, limit?: number}, callback: (candles: Candle[], snapshot: boolean) => void, onError?: (error: Error) => void): () => void;
1426
1429
  }
1427
1430
 
1428
1431
  /** Open order of a tracked account */
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
  */