forked from Brahma-fi/console-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
347 lines (319 loc) · 11.1 KB
/
Copy pathindex.ts
File metadata and controls
347 lines (319 loc) · 11.1 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import axios, { AxiosError, AxiosInstance } from "axios";
import { Address } from "viem";
import routes from "@/routes";
import {
Account,
ActionNameToId,
BridgeParams,
BridgeRoute,
GenerateCalldataResponse,
GeneratePayload,
GetBridgingRoutesParams,
GetBridgingStatus,
SendParams,
SolverParams,
SwapParams,
SwapQuoteRoute
} from "./types";
export class CoreActions {
private readonly axiosInstance: AxiosInstance;
constructor(apiKey: string, baseURL: string) {
this.axiosInstance = axios.create({
baseURL,
headers: {
"x-api-key": apiKey
}
});
}
/**
* Fetches existing accounts associated with a given Externally Owned Account (EOA).
*
* @param {Address} eoa - The address of EOA to fetch Accounts for.
* @returns {Promise<Account[]>} A promise that resolves to an array of Accounts.
* @throws Will return an empty array if no accounts are found or if an error occurs during the fetch.
*/
async fetchExistingAccounts(eoa: Address): Promise<Account[]> {
try {
if (!eoa) {
throw new Error("EOA (Externally Owned Account) is required");
}
const response = await this.axiosInstance.get<{ data: Account[] }>(
`${routes.fetchExistingAccounts}/${eoa}`
);
if (!response.data.data) {
throw new Error("No accounts found for the given EOA");
}
return response.data.data;
} catch (err: any) {
console.error(`Error fetching existing accounts: ${err.message}`);
return [];
}
}
/**
* Initiates a send action to generate calldata for transferring tokens on a blockchain network.
*
* @param {number} chainId - The ID of the blockchain network.
* @param {Address} accountAddress - The address of the account sending the tokens.
* @param {SendParams} params - The parameters for the send action, including recipient and token details.
* @returns {Promise<GenerateCalldataResponse>} A promise that resolves to a GenerateCalldataResponse object containing the transaction data.
* @throws Will throw an error if the calldata generation fails.
*/
async send(
chainId: number,
accountAddress: Address,
params: SendParams
): Promise<GenerateCalldataResponse> {
try {
const response = await this.axiosInstance.post<GenerateCalldataResponse>(
routes.generateCalldata,
{
id: "INTENT",
action: "BUILD",
params: {
id: ActionNameToId.send,
chainId: chainId,
consoleAddress: accountAddress,
params
}
} as GeneratePayload<SendParams, "BUILD">
);
return response.data;
} catch (err: any) {
console.error(`Error generating calldata: ${err.message}`);
throw err;
}
}
/**
* Initiates a swap action to generate calldata for swapping assets on a blockchain network.
*
* @param {number} chainId - The ID of the blockchain network.
* @param {Address} accountAddress - The address of the account performing the swap.
* @param {SwapParams} params - The parameters for the swap action.
* @returns {Promise<GenerateCalldataResponse>} A promise that resolves to a GenerateCalldataResponse object containing the transaction data.
* @throws Will throw an error if the calldata generation fails.
*/
async swap(
chainId: number,
accountAddress: Address,
params: SwapParams
): Promise<GenerateCalldataResponse> {
try {
const response = await this.axiosInstance.post<GenerateCalldataResponse>(
routes.generateCalldata,
{
id: "INTENT",
action: "BUILD",
params: {
id: ActionNameToId.swap,
chainId: chainId,
consoleAddress: accountAddress,
params
}
} as GeneratePayload<SwapParams, "BUILD">
);
return response.data;
} catch (err: any) {
console.error(`Error generating calldata: ${err.message}`);
throw err;
}
}
/**
* Fetches swap routes for a given asset pair and amount.
*
* @param {Address} fromAssetAddress - The address of the asset to swap from.
* @param {Address} toAssetAddress - The address of the asset to swap to.
* @param {Address} ownerAddress - The address of the owner initiating the swap.
* @param {string} fromAmount - The amount of the asset to swap from.
* @param {string} slippage - The acceptable slippage percentage for the swap.
* @param {number} chainId - The ID of the blockchain network.
* @returns {Promise<{ data: SwapQuoteRoute[]; error?: string }>} A promise that resolves to an object containing the swap routes data or an error message.
* @throws Will return an error message if the request fails.
*/
async getSwapRoutes(
fromAssetAddress: Address,
toAssetAddress: Address,
ownerAddress: Address,
fromAmount: string,
slippage: string,
chainId: number
): Promise<{ data: SwapQuoteRoute[]; error?: string }> {
const requestData = {
chainId,
fromAssetAddress,
toAssetAddress,
ownerAddress,
fromAmount,
slippage
};
try {
const params = new URLSearchParams();
Object.entries(requestData).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v) => params.append(key, v));
} else {
params.set(key, value.toString());
}
});
const queryString = params.toString();
const response = await this.axiosInstance.get<SwapQuoteRoute[]>(
`${routes.swapRoutes}?${queryString}`
);
return { data: response.data, error: undefined };
} catch (err: any) {
const error = err as AxiosError<{ message: string }>;
return {
data: [],
error: error.response?.data?.message ?? error.message
};
}
}
/**
* Initiates a bridge action to generate calldata for bridging assets between blockchain networks.
*
* @param {number} chainId - The ID of the blockchain network.
* @param {Address} accountAddress - The address of the account performing the bridge.
* @param {BridgeParams} params - The parameters for the bridge action.
* @returns {Promise<GenerateCalldataResponse>} A promise that resolves to a GenerateCalldataResponse object containing the transaction data.
* @throws Will throw an error if the calldata generation fails.
*/
async bridge(
chainId: number,
accountAddress: Address,
params: BridgeParams
): Promise<GenerateCalldataResponse> {
try {
const response = await this.axiosInstance.post<GenerateCalldataResponse>(
routes.generateCalldata,
{
id: "INTENT",
action: "BUILD",
params: {
id: ActionNameToId.bridging,
chainId: chainId,
consoleAddress: accountAddress,
params
}
} as GeneratePayload<BridgeParams, "BUILD">
);
return response.data;
} catch (err: any) {
console.error(`Error generating calldata: ${err.message}`);
throw err;
}
}
/**
* Fetches bridging routes based on the specified parameters.
* @param {GetBridgingRoutesParams} params - The parameters for fetching bridging routes.
* @returns {Promise<BridgeRoute[]>} A promise that resolves to an array of BridgeRoute objects.
*/
async fetchBridgingRoutes(
params: GetBridgingRoutesParams
): Promise<BridgeRoute[]> {
try {
const query = new URLSearchParams({
chainIdIn: params.chainIdIn.toString(),
chainIdOut: params.chainIdOut.toString(),
tokenIn: params.tokenIn,
tokenOut: params.tokenOut,
amountIn: params.amountIn.toString(),
amountOut: params.amountOut.toString(),
slippage: params.slippage.toString(),
ownerAddress: params.ownerAddress,
recipient: params.recipient
}).toString();
const url = `${routes.fetchBridgingRoutes}?${query}`;
const response = await this.axiosInstance.get<BridgeRoute[]>(url);
return response.data || [];
} catch (err: any) {
console.error(`Error fetching bridging routes: ${err.message}`);
return [];
}
}
/**
* Fetches the status of a bridging transaction.
* @param {Address} txnHash - The transaction hash.
* @param {number} pid - The process ID.
* @param {number} fromChainId - The ID of the source blockchain network.
* @param {number} toChainId - The ID of the destination blockchain network.
* @returns {Promise<GetBridgingStatus | null>} A promise that resolves to a GetBridgingStatus object or null.
*/
async fetchBridgingStatus(
txnHash: Address,
pid: number,
fromChainId: number,
toChainId: number
): Promise<GetBridgingStatus | null> {
try {
const queryParams = new URLSearchParams({
pid: pid.toString(),
transactionHash: txnHash,
fromChainId: fromChainId.toString(),
toChainId: toChainId.toString()
});
const response = await this.axiosInstance.get<GetBridgingStatus>(
`${routes.fetchBridgingStatus}?${queryParams.toString()}`
);
return response.data;
} catch (err: any) {
return null;
}
}
/**
* Indexes a transaction on the blockchain.
* @param {string} transactionHash - The hash of the transaction to index.
* @param {number} chainID - The ID of the blockchain network.
* @returns {Promise<void>} A promise that resolves when the transaction is indexed.
*/
async indexTransaction(
transactionHash: string,
chainID: number
): Promise<void> {
try {
const response = await this.axiosInstance.post(
`${routes.indexTransaction}/${transactionHash}/${chainID}`
);
if (response.status !== 204) {
throw new Error("Failed to index transaction");
}
console.log("Transaction indexed successfully");
} catch (err: any) {
console.error(`Error indexing transaction: ${err.message}`);
throw err;
}
}
/**
* Initiates a bridge action to generate solver calldata for a transaction.
*
* @param {Address} accountAddress - The address of the account performing the transaction.
* @param {SolverParams} params - The parameters for the solver action.
* @returns {Promise<GenerateCalldataResponse>} A promise that resolves to a GenerateCalldataResponse object containing the transaction data.
* @throws Will throw an error if the calldata generation fails.
*/
async solver(
accountAddress: Address,
params: SolverParams
): Promise<GenerateCalldataResponse> {
try {
const response = await this.axiosInstance.post<GenerateCalldataResponse>(
routes.generateCalldata,
{
id: "INTENT",
action: "BUILD",
params: {
id: ActionNameToId.solver,
chainId: params.chainId,
consoleAddress: accountAddress,
params: {
...params,
slippage: params.slippage * 1e2 // 4 basis points
}
}
} as GeneratePayload<SolverParams, "BUILD">
);
return response.data;
} catch (err: any) {
console.error(`Error generating calldata: ${err.message}`);
throw err;
}
}
}