@axis-markets/client 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/errors.js CHANGED
@@ -1,4 +1,4 @@
1
- import {contract} from '@stellar/stellar-sdk'
1
+ import {StrKey, contract} from '@stellar/stellar-sdk'
2
2
 
3
3
  /**
4
4
  * Standard contract errors
@@ -59,22 +59,34 @@ export function processSimulationErrors(tx) {
59
59
  const contractErrorMatch = /HostError: Error\(Contract, #(\d+)\)/.exec(message)
60
60
  if (contractErrorMatch) {
61
61
  const code = parseInt(contractErrorMatch[1], 10)
62
- const source = findErrorSource(message, code)
63
- const dexContract = tx.options?.contractId
64
- const raisedByToken = source && dexContract ? source.contract !== dexContract : !ContractErrors[code] && !!TokenErrors[code]
65
- if (raisedByToken)
66
- throw tokenError(code, source?.contract)
67
- const err = ContractErrors[code]
68
- if (err) {
69
- const error = new Error(`Contract execution error: #${code} ${err.message}`)
70
- error.code = code
62
+ const error = contractError(code, findErrorSource(message, code)?.contract, tx.options?.contractId)
63
+ if (error)
71
64
  throw error
72
- }
73
65
  }
74
66
  throw message
75
67
  }
76
68
  }
77
69
 
70
+ /**
71
+ * Wrapped aggregated error - token error when another contract than the DEX raised it, a DEX contract error otherwise
72
+ * @param {number} code - Contract error code
73
+ * @param {string} [source] - Contract that raised the error, when known
74
+ * @param {string} [dexContract] - DEX contract address, when known
75
+ * @return {Error|null} - Null for an unknown code of the DEX
76
+ * @private
77
+ */
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)
84
+ return null
85
+ const error = new Error(`Contract execution error: #${code} ${err.message}`)
86
+ error.code = code
87
+ return error
88
+ }
89
+
78
90
  /**
79
91
  * Locate the contract that raised the error in a simulation event log. The log lists events newest first and an error
80
92
  * is re-emitted by every frame it fails, so the oldest `error` event with the code is where it was raised (errors of
@@ -115,17 +127,134 @@ function tokenError(code, contract) {
115
127
  }
116
128
 
117
129
  /**
118
- * Handle the failure of a transaction applied on-chain
119
- * @param {contract.SentTransaction} sent
120
- * @throws {Error} - Error with the transaction `hash` and its result
130
+ * Transaction-related error
131
+ * @param {'ERROR'|'TRY_AGAIN_LATER'|'FAILED'|'TIMEOUT'} status - `ERROR`: rejected with a result code (`errorResult`
132
+ * of `sendTransaction`), `TRY_AGAIN_LATER`: not accepted for now (congestion, or another transaction of the account
133
+ * pending), `FAILED`: applied and failed, `TIMEOUT`: not seen before its time bounds expired
134
+ * @param {{hash?: string, result?: xdr.TransactionResult, resultCode?: string, events?: xdr.DiagnosticEvent[], contractId?: string}} [details] -
135
+ * Transaction hash, its result (or its result code, when known without the result), the diagnostic events of a failed
136
+ * call and the DEX contract address
137
+ * @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
121
140
  * @internal
122
141
  */
123
- export function processTransactionErrors(sent) {
124
- const response = sent.getTransactionResponse
125
- if (response?.status !== 'FAILED')
126
- return
127
- const hash = sent.sendTransactionResponse?.hash
128
- const error = new Error(`Transaction ${hash} failed: ${JSON.stringify(response.resultXdr?.result, (key, value) => typeof value === 'bigint' ? value.toString() : value)}`)
142
+ export function transactionError(status, {hash, result, resultCode: knownCode, events, contractId} = {}) {
143
+ const resultCode = knownCode ?? (result?.result?.type ? snakeCase(result.result.type) : undefined)
144
+ const opResult = operationResultCode(result)
145
+ const cause = events?.length ? findEventError(events) : undefined
146
+ const causeError = cause ? contractError(cause.code, cause.contract, contractId) : null
147
+ let message
148
+ switch (status) {
149
+ case 'ERROR':
150
+ message = `Transaction ${hash} was not accepted by the network: ${resultCode ?? 'unknown result'}`
151
+ break
152
+ case 'TRY_AGAIN_LATER':
153
+ message = `Transaction ${hash} was not accepted by the network for now, try again later`
154
+ break
155
+ case 'FAILED':
156
+ message = `Transaction ${hash} failed: ${resultCode ?? 'unknown result'}${opResult ? ` (${opResult})` : ''}`
157
+ break
158
+ default:
159
+ message = `Transaction ${hash} was not confirmed before its time bounds expired`
160
+ }
161
+ if (causeError) {
162
+ message += `. ${causeError.message}`
163
+ }
164
+ const error = new Error(message)
165
+ error.status = status
129
166
  error.hash = hash
130
- throw error
167
+ if (resultCode) {
168
+ error.result = resultCode
169
+ }
170
+ if (opResult) {
171
+ error.opResult = opResult
172
+ }
173
+ if (causeError) {
174
+ error.code = causeError.code
175
+ if (causeError.tokenError) {
176
+ error.tokenError = true
177
+ if (causeError.contract) {
178
+ error.contract = causeError.contract
179
+ }
180
+ }
181
+ }
182
+ return error
183
+ }
184
+
185
+ /**
186
+ * Code of the first failed operation of a `tx_failed` result
187
+ * @param {xdr.TransactionResult} [result]
188
+ * @return {string|undefined} - Horizon-style code, e.g. `invoke_host_function_trapped`
189
+ * @private
190
+ */
191
+ function operationResultCode(result) {
192
+ if (result?.result?.type !== 'txFailed')
193
+ return undefined
194
+ for (const op of result.result.results || []) {
195
+ //an applied operation reports its own result code, an operation that could not run the outer code
196
+ const code = op.type === 'opInner' ? op.tr?.value?.type : op.type
197
+ if (code && !/Success$/.test(code))
198
+ return snakeCase(code)
199
+ }
200
+ return undefined
201
+ }
202
+
203
+ /**
204
+ * 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
207
+ * @param {xdr.DiagnosticEvent[]} events
208
+ * @return {{code: number, contract?: string}|undefined}
209
+ * @private
210
+ */
211
+ function findEventError(events) {
212
+ const errors = []
213
+ for (const event of events) {
214
+ const code = eventErrorCode(event)
215
+ if (code !== undefined) {
216
+ errors.push({code, contract: eventContract(event)})
217
+ }
218
+ }
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}
223
+ }
224
+
225
+ /**
226
+ * Contract error code of an `error` diagnostic event
227
+ * @param {xdr.DiagnosticEvent} event
228
+ * @return {number|undefined}
229
+ * @private
230
+ */
231
+ function eventErrorCode(event) {
232
+ const topics = event?.event?.body?.value?.topics
233
+ if (!topics || topics.length < 2)
234
+ return undefined
235
+ const [name, value] = topics
236
+ if (name.type !== 'scvSymbol' || name.sym.toString() !== 'error')
237
+ return undefined
238
+ if (value.type !== 'scvError' || value.error.type !== 'sceContract')
239
+ return undefined
240
+ return value.error.contractCode
241
+ }
242
+
243
+ /**
244
+ * @param {xdr.DiagnosticEvent} event
245
+ * @return {string|undefined} - Address of the contract that emitted the event
246
+ * @private
247
+ */
248
+ function eventContract(event) {
249
+ const id = event.event.contractId
250
+ return id ? StrKey.encodeContract(id.toBytes()) : undefined
251
+ }
252
+
253
+ /**
254
+ * @param {string} name - XDR union arm name, e.g. `txBadSeq`
255
+ * @return {string} - Horizon-style code, e.g. `tx_bad_seq`
256
+ * @private
257
+ */
258
+ function snakeCase(name) {
259
+ return name.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase())
131
260
  }