forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsuiService.ts
More file actions
553 lines (489 loc) · 14.5 KB
/
Copy pathsuiService.ts
File metadata and controls
553 lines (489 loc) · 14.5 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import { resolveRpcUrl } from '@/lib/appConfig';
import { appStore } from '@/lib/store';
import {
Network,
ChainId,
SuiRpcResponse,
BuilderArg,
RPCHealthMetric,
} from '../types';
import { EVM_NETWORKS, STELLAR_NETWORKS } from '@/lib/constants';
const RPC_TIMEOUT_MS = 10000;
const DEGRADED_RPC_LATENCY_MS = 1500;
export class SuiRpcError extends Error {
status: number;
endpoint: string;
duration: number;
constructor(
message: string,
{
status,
endpoint,
duration,
}: {
status: number;
endpoint: string;
duration: number;
}
) {
super(message);
this.name = 'SuiRpcError';
this.status = status;
this.endpoint = endpoint;
this.duration = duration;
Object.setPrototypeOf(this, SuiRpcError.prototype);
}
}
export const getActiveSuiRpcUrl = (
network: Network
) =>
resolveRpcUrl(
network,
appStore.getSnapshot().settings
);
export const resolveChainRpcUrl = (
chain: ChainId,
network: Network
): string => {
if (chain === 'sui') {
return getActiveSuiRpcUrl(network);
}
const map = chain === 'evm' ? EVM_NETWORKS : STELLAR_NETWORKS;
return map[network];
};
/** Generic JSON-RPC fetch used for all chains. */
export const executeChainRpc = async (
chain: ChainId,
network: Network,
method: string,
params: any[]
): Promise<{ result: any; duration: number; status: number }> => {
if (chain === 'sui') {
return executeSuiRpc(network, method, params);
}
const url = resolveChainRpcUrl(chain, network);
const startTime = performance.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
RPC_TIMEOUT_MS
);
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method,
params,
}),
signal: controller.signal
});
clearTimeout(timeoutId);
const data = await response.json();
const duration = Math.round(
performance.now() - startTime
);
if (!response.ok) {
const message =
typeof data.error?.message === 'string' && data.error.message
? data.error.message
: `RPC request failed with status ${response.status}.`;
throw new SuiRpcError(message, {
status: response.status,
endpoint: url,
duration,
});
}
if (data.error) {
const message =
typeof data.error.message === 'string' && data.error.message
? data.error.message
: `${chain.toUpperCase()} RPC returned an error.`;
throw new SuiRpcError(message, {
status: response.status || 500,
endpoint: url,
duration,
});
}
return {
result: data.result,
duration,
status: response.status,
};
} catch (error: any) {
const duration = Math.round(
performance.now() - startTime
);
if (error instanceof SuiRpcError) {
throw error;
}
if (error?.name === 'AbortError') {
throw new SuiRpcError(
`RPC request timed out after ${RPC_TIMEOUT_MS / 1000}s.`,
{ status: 504, endpoint: url, duration }
);
}
throw new SuiRpcError(
error instanceof Error && error.message.trim()
? error.message
: `Unable to reach the configured ${chain.toUpperCase()} RPC endpoint.`,
{ status: 0, endpoint: url, duration }
);
}
};
/** Chain-aware health check: pings a lightweight method per chain. */
export const getChainRpcHealth = async (
chain: ChainId,
network: Network
): Promise<RPCHealthMetric> => {
if (chain === 'sui') {
return getSuiRpcHealth(network);
}
const url = resolveChainRpcUrl(chain, network);
const method = chain === 'evm' ? 'eth_blockNumber' : 'getHealth';
const params: any[] = chain === 'evm' ? [] : [];
try {
const { result, duration } =
await executeChainRpc(chain, network, method, params);
return {
endpoint: url,
latency: [duration],
successRate: 1,
status: duration >= DEGRADED_RPC_LATENCY_MS ? 'degraded' : 'healthy',
blockHeight: typeof result === 'string' ? parseInt(result, 16) || 0 : Number(result) || 0,
};
} catch (error) {
const rpcError = error instanceof SuiRpcError ? error : null;
return {
endpoint: url,
latency: [rpcError?.duration ?? RPC_TIMEOUT_MS],
successRate: 0,
status: rpcError?.status === 504 ? 'degraded' : 'down',
blockHeight: 0,
};
}
};
export const executeSuiRpc = async (
network: Network,
method: string,
params: any[]
): Promise<{ result: any; duration: number; status: number }> => {
const url = getActiveSuiRpcUrl(network);
const startTime = performance.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
RPC_TIMEOUT_MS
);
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method,
params,
}),
signal: controller.signal
});
clearTimeout(timeoutId);
const data: SuiRpcResponse = await response.json();
const duration = Math.round(
performance.now() - startTime
);
if (!response.ok) {
const message =
typeof data.error?.message ===
'string' && data.error.message
? data.error.message
: `RPC request failed with status ${response.status}.`;
throw new SuiRpcError(message, {
status: response.status,
endpoint: url,
duration,
});
}
if (data.error) {
const message =
typeof data.error.message ===
'string' && data.error.message
? data.error.message
: 'Sui RPC returned an error.';
throw new SuiRpcError(message, {
status: response.status || 500,
endpoint: url,
duration,
});
}
return {
result: data.result,
duration,
status: response.status,
};
} catch (error: any) {
const duration = Math.round(
performance.now() - startTime
);
if (error instanceof SuiRpcError) {
throw error;
}
if (error?.name === 'AbortError') {
throw new SuiRpcError(
`RPC request timed out after ${RPC_TIMEOUT_MS / 1000}s.`,
{
status: 504,
endpoint: url,
duration,
}
);
}
throw new SuiRpcError(
error instanceof Error &&
error.message.trim()
? error.message
: 'Unable to reach the configured Sui RPC endpoint.',
{
status: 0,
endpoint: url,
duration,
}
);
}
};
export const getSuiRpcHealth =
async (
network: Network
): Promise<RPCHealthMetric> => {
const endpoint =
getActiveSuiRpcUrl(network);
try {
const { result, duration } =
await executeSuiRpc(
network,
'sui_getLatestCheckpointSequenceNumber',
[]
);
const blockHeight =
Number.parseInt(
String(result),
10
) || 0;
return {
endpoint,
latency: [duration],
successRate: 1,
status:
duration >=
DEGRADED_RPC_LATENCY_MS
? 'degraded'
: 'healthy',
blockHeight,
};
} catch (error) {
const rpcError =
error instanceof SuiRpcError
? error
: null;
return {
endpoint,
latency: [
rpcError?.duration ??
RPC_TIMEOUT_MS,
],
successRate: 0,
status:
rpcError?.status === 504
? 'degraded'
: 'down',
blockHeight: 0,
};
}
};
// ─── SuiNS resolution ────────────────────────────────────────────────────
// Sui RPC methods that take an "owner" expect a 0x-prefixed hex address.
// These helpers let callers pass either a raw address or a SuiNS name
// like `aliphatic.sui` and auto-resolve through `suix_resolveNameServiceAddress`.
const SUI_ADDRESS_RE = /^0x[0-9a-fA-F]{1,64}$/;
const SUI_NS_RE = /^[a-z0-9-]+(\.[a-z0-9-]+)*\.sui$/i;
export const looksLikeSuiAddress = (value: string): boolean =>
SUI_ADDRESS_RE.test(value.trim());
export const looksLikeSuiNs = (value: string): boolean =>
SUI_NS_RE.test(value.trim());
const SUI_NS_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
type SuiNsCacheEntry = { address: string; expiresAt: number };
const suiNsCache = new Map<string, SuiNsCacheEntry>();
const cacheKey = (network: Network, name: string) => `${network}:${name.trim().toLowerCase()}`;
/**
* Resolve a Sui address or SuiNS name to a raw 0x address.
* Returns the input unchanged if it already looks like an address.
* Throws SuiRpcError if the name cannot be resolved.
*/
export const resolveSuiAddress = async (
network: Network,
input: string,
): Promise<string> => {
const value = input.trim();
if (looksLikeSuiAddress(value)) return value;
if (!looksLikeSuiNs(value)) {
// Pass through unchanged — let the underlying RPC reject if invalid.
return value;
}
const key = cacheKey(network, value);
const cached = suiNsCache.get(key);
if (cached) {
if (cached.expiresAt > Date.now()) {
return cached.address;
}
suiNsCache.delete(key);
}
const { result } = await executeSuiRpc(network, 'suix_resolveNameServiceAddress', [value]);
if (typeof result !== 'string' || !looksLikeSuiAddress(result)) {
throw new SuiRpcError(`Could not resolve ${value}`, {
status: 200,
endpoint: getActiveSuiRpcUrl(network),
duration: 0,
});
}
suiNsCache.set(key, { address: result, expiresAt: Date.now() + SUI_NS_CACHE_TTL_MS });
return result;
};
export const simulateMoveCall = async (
network: Network,
sender: string,
packageId: string,
module: string,
func: string,
typeArgs: string[],
args: BuilderArg[]
) => {
// Convert BuilderArgs to raw arguments for simulation/inspection
// For simulation, we can often pass pure values as is, and object IDs as strings
const rawArgs = args.map(arg => {
if (arg.type === 'u64' || arg.type === 'u128' || arg.type === 'u256') {
return arg.value; // Passed as string to avoid precision loss
}
if (arg.type === 'u8' || arg.type === 'u16' || arg.type === 'u32') {
return parseInt(arg.value);
}
if (arg.type === 'bool') {
return arg.value === 'true';
}
// Address, String, Object ID, etc.
return arg.value;
});
const resolvedSender = await resolveSuiAddress(network, sender);
const method = 'sui_devInspectTransactionBlock';
const params = [
resolvedSender,
{
kind: 'moveCall',
target: `${packageId}::${module}::${func}`,
typeArguments: typeArgs,
arguments: rawArgs
},
null,
null
];
return executeSuiRpc(network, method, params);
};
export const getOwnedObjects = async (network: Network, address: string) => {
const resolved = await resolveSuiAddress(network, address);
return executeSuiRpc(network, 'suix_getOwnedObjects', [
resolved,
{ options: { showType: true, showContent: true, showDisplay: true } }
]);
};
export const getObject = async (network: Network, objectId: string) => {
return executeSuiRpc(network, 'sui_getObject', [
objectId,
{ showType: true, showContent: true, showOwner: true }
]);
};
export const getBalance = async (network: Network, owner: string) => {
const resolved = await resolveSuiAddress(network, owner);
return executeSuiRpc(network, 'suix_getBalance', [
resolved,
'0x2::sui::SUI'
]);
};
export const signAndExecuteMoveCall = async (
network: Network,
sender: string,
packageId: string,
module: string,
func: string,
typeArgs: string[],
args: BuilderArg[],
signAndExecuteTransaction: (transactionBlock: any) => Promise<any>
) => {
const resolvedSender = await resolveSuiAddress(network, sender);
// Import Transaction dynamically to avoid circular dependencies
const { Transaction } = await import('@mysten/sui/transactions');
const txb = new Transaction();
// Convert BuilderArgs into typed transaction arguments
const txArgs = args.map(arg => {
switch (arg.type) {
case 'u8':
return txb.pure.u8(parseInt(arg.value, 10));
case 'u16':
return txb.pure.u16(parseInt(arg.value, 10));
case 'u32':
return txb.pure.u32(parseInt(arg.value, 10));
case 'u64':
return txb.pure.u64(arg.value); // Passed as string to avoid precision loss
case 'u128':
return txb.pure.u128(arg.value);
case 'u256':
return txb.pure.u256(arg.value);
case 'bool':
return txb.pure.bool(arg.value === 'true');
case 'address':
return txb.pure.address(arg.value);
case 'object':
return txb.object(arg.value);
case 'vector<u8>':
return txb.pure.vector('u8', arg.value.split(',').map(v => parseInt(v.trim(), 10)));
case 'vector<address>':
return txb.pure.vector('address', arg.value.split(',').map(v => v.trim()));
default:
return txb.pure.string(arg.value);
}
});
txb.moveCall({
target: `${packageId}::${module}::${func}`,
typeArguments: typeArgs,
arguments: txArgs
});
try {
const result = await signAndExecuteTransaction(txb);
return {
result: {
digest: result.digest,
transaction: result.transaction,
effects: result.effects,
confirmed: true,
executed: true
},
duration: 0,
status: 200
};
} catch (error: any) {
throw new SuiRpcError(
error instanceof Error && error.message.trim()
? error.message
: 'Transaction signing or execution failed.',
{
status: 500,
endpoint: getActiveSuiRpcUrl(network),
duration: 0,
}
);
}
};