-
Notifications
You must be signed in to change notification settings - Fork 29
/
rpc.ts
72 lines (64 loc) · 2.01 KB
/
rpc.ts
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
const randomId = () => Math.floor(Math.random() * 10000000000);
export const send = (provider: any, method: string, params?: any[]) => new Promise<any>((resolve, reject) => {
const payload = {
id: randomId(),
method,
params,
};
const callback = (err: any, result: any) => {
if (err) {
reject(err);
} else if (result.error) {
console.error(result.error);
reject(result.error);
} else {
resolve(result.result);
}
};
let _provider = provider.provider || provider
if (_provider.sendAsync) {
_provider.sendAsync(payload, callback);
} else {
_provider.send(payload, callback).catch((error: any) => {
if (
error.message ===
"Hardhat Network doesn't support JSON-RPC params sent as an object"
) {
_provider
.send(method, params)
.then((r: any) => resolve(r))
.catch((e: any) => reject(e));
} else {
throw error;
}
});
}
});
export interface RSV {
r: string;
s: string;
v: number;
}
export const signData = async (provider: any, fromAddress: string, typeData: any): Promise<RSV> => {
const typeDataString = typeof typeData === 'string' ? typeData : JSON.stringify(typeData);
const result = await send(provider, 'eth_signTypedData_v4', [fromAddress, typeDataString])
.catch((error: any) => {
if (error.message === 'Method eth_signTypedData_v4 not supported.') {
return send(provider, 'eth_signTypedData', [fromAddress, typeData]);
} else {
throw error;
}
});
return {
r: result.slice(0, 66),
s: '0x' + result.slice(66, 130),
v: parseInt(result.slice(130, 132), 16),
};
};
let chainIdOverride: null | number = null;
export const setChainIdOverride = (id: number) => { chainIdOverride = id };
export const getChainId = async (provider: any): Promise<any> => chainIdOverride || send(provider, 'eth_chainId');
export const call = (provider: any, to: string, data: string) => send(provider, 'eth_call', [{
to,
data,
}, 'latest']);