-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathtransaction.ts
More file actions
314 lines (294 loc) · 8.66 KB
/
transaction.ts
File metadata and controls
314 lines (294 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { type Address, type TransactionReceipt } from 'viem'
import { LogLevel } from './logger.js'
import type {
Execute,
AdaptedWallet,
TransactionStepItem,
paths,
SvmReceipt
} from '../types/index.js'
import { axios } from '../utils/axios.js'
import type {
AxiosRequestConfig,
AxiosRequestHeaders,
AxiosResponse
} from 'axios'
import { getClient } from '../client.js'
import { SolverStatusTimeoutError } from '../errors/index.js'
import { repeatUntilOk } from '../utils/repeatUntilOk.js'
/**
* Safe txhash.wait which handles replacements when users speed up the transaction
* @param url an URL object
* @returns A Promise to wait on
*/
export async function sendTransactionSafely(
chainId: number,
item: TransactionStepItem,
step: Execute['steps'][0],
wallet: AdaptedWallet,
setTxHashes: (
tx: NonNullable<Execute['steps'][0]['items']>[0]['txHashes']
) => void,
setInternalTxHashes: (
tx: NonNullable<Execute['steps'][0]['items']>[0]['internalTxHashes']
) => void,
request: AxiosRequestConfig,
headers?: AxiosRequestHeaders,
crossChainIntentChainId?: number,
isValidating?: (res?: AxiosResponse<any, any>) => void,
details?: Execute['details']
) {
const client = getClient()
try {
//In some cases wallets can be delayed when switching chains, causing this check to fail.
//To work around this we check the chain id of the active wallet a few times before declaring it a failure
await repeatUntilOk(
async () => {
const walletChainId = await wallet.getChainId()
return walletChainId === chainId
},
10,
undefined,
250
)
} catch (e) {
const walletChainId = await wallet.getChainId()
throw `Current chain id: ${walletChainId} does not match expected chain id: ${chainId} `
}
let receipt: TransactionReceipt | SvmReceipt | undefined
let transactionCancelled = false
const pollingInterval = client.pollingInterval ?? 5000
const maximumAttempts =
client.maxPollingAttemptsBeforeTimeout ??
(2.5 * 60 * 1000) / pollingInterval // default to 2 minutes and 30 seconds worth of attempts
let waitingForConfirmation = true
let attemptCount = 0
let txHash = await wallet.handleSendTransactionStep(chainId, item, step)
if ((txHash as any) === 'null') {
throw 'User rejected the request'
}
postTransactionToSolver({
txHash,
chainId,
step,
request,
headers
})
if (!txHash) {
throw Error(
'Transaction hash not returned from handleSendTransactionStep method'
)
}
setTxHashes([{ txHash: txHash, chainId: chainId }])
//Set up internal functions
const validate = (res: AxiosResponse) => {
getClient()?.log(
['Execute Steps: Polling for confirmation', res],
LogLevel.Verbose
)
if (res.status === 200 && res.data && res.data.status === 'failure') {
throw Error('Transaction failed')
}
if (res.status === 200 && res.data && res.data.status === 'fallback') {
throw Error('Transaction failed: Refunded')
}
if (res.status === 200 && res.data && res.data.status === 'success') {
if (txHash) {
setInternalTxHashes([{ txHash: txHash, chainId: chainId }])
}
const chainTxHashes: NonNullable<
Execute['steps'][0]['items']
>[0]['txHashes'] = res.data?.txHashes?.map((hash: Address) => {
return {
txHash: hash,
chainId: res?.data?.destinationChainId ?? crossChainIntentChainId
}
})
setTxHashes(chainTxHashes)
return true
}
return false
}
// Poll the confirmation url to confirm the transaction went through
const pollForConfirmation = async () => {
isValidating?.()
while (
waitingForConfirmation &&
attemptCount < maximumAttempts &&
!transactionCancelled
) {
let res
if (item?.check?.endpoint && !request?.data?.useExternalLiquidity) {
res = await axios.request({
url: `${request.baseURL}${item?.check?.endpoint}`,
method: item?.check?.method,
headers: headers
})
}
if (!res || validate(res)) {
waitingForConfirmation = false // transaction confirmed
} else if (res) {
if (res.data.status !== 'pending') {
isValidating?.(res)
attemptCount++
}
await new Promise((resolve) => setTimeout(resolve, pollingInterval))
}
}
if (attemptCount >= maximumAttempts) {
throw new SolverStatusTimeoutError(txHash as Address, attemptCount)
}
if (transactionCancelled) {
throw Error('Transaction was cancelled')
}
return true
}
const waitForTransaction = () => {
const controller = new AbortController()
const signal = controller.signal
// Handle transaction replacements and cancellations
return {
promise: wallet
.handleConfirmTransactionStep(
txHash as string,
chainId,
(replacementTxHash) => {
if (signal.aborted) {
return
}
setTxHashes([{ txHash: replacementTxHash, chainId: chainId }])
txHash = replacementTxHash
attemptCount = 0 // reset attempt count
getClient()?.log(
['Transaction replaced', replacementTxHash],
LogLevel.Verbose
)
postTransactionToSolver({
txHash: replacementTxHash as Address,
chainId,
step,
request,
headers
})
},
() => {
if (signal.aborted) {
return
}
transactionCancelled = true
getClient()?.log(['Transaction cancelled'], LogLevel.Verbose)
}
)
.then((data) => {
if (signal.aborted) {
return
}
receipt = data
getClient()?.log(
['Transaction Receipt obtained', receipt],
LogLevel.Verbose
)
})
.catch((error) => {
if (signal.aborted) {
return
}
getClient()?.log(
['Error in handleConfirmTransactionStep', error],
LogLevel.Error
)
if (error.message === 'Transaction cancelled') {
transactionCancelled = true
}
}),
controller
}
}
//If the origin chain is bitcoin, skip polling for confirmation, because the deposit will take too long
if (chainId === 8253038) {
return true
}
//Sequence internal functions
// We want synchronous execution in the following cases:
// - Approval Signature step required first
// - Bitcoin is the destination
// - Canonical route used
if (
step.id === 'approve' ||
details?.currencyOut?.currency?.chainId === 8253038 ||
request?.data?.useExternalLiquidity
) {
await waitForTransaction().promise
//In the following cases we want to skip polling for confirmation:
// - Bitcoin destination chain, we want to skip polling for confirmation as the block times are lengthy
// - Canonical route, also lengthy fill time
if (
details?.currencyOut?.currency?.chainId !== 8253038 &&
!request?.data?.useExternalLiquidity
) {
await pollForConfirmation()
}
} else {
const { promise: receiptPromise, controller: receiptController } =
waitForTransaction()
const confirmationPromise = pollForConfirmation()
await Promise.race([receiptPromise, confirmationPromise])
if (waitingForConfirmation) {
await confirmationPromise
}
if (!receipt) {
if (!item.check) {
await receiptPromise
} else {
receiptController.abort()
}
}
}
return true
}
const postTransactionToSolver = async ({
txHash,
chainId,
request,
headers,
step
}: {
txHash: string | undefined
chainId: number
step: Execute['steps'][0]
request: AxiosRequestConfig
headers?: AxiosRequestHeaders
}) => {
if (step.id === 'deposit' && txHash) {
getClient()?.log(
['Posting transaction to notify the solver'],
LogLevel.Verbose
)
try {
const triggerData: NonNullable<
paths['/transactions/index']['post']['requestBody']
>['content']['application/json'] = {
txHash,
chainId: chainId.toString()
}
axios
.request({
url: `${request.baseURL}/transactions/index`,
method: 'POST',
headers: headers,
data: triggerData
})
.then(() => {
getClient()?.log(
['Transaction notified to the solver'],
LogLevel.Verbose
)
})
} catch (e) {
getClient()?.log(
['Failed to post transaction to solver', e],
LogLevel.Warn
)
}
}
}