@etherplay/connect 0.0.9 → 0.0.11

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.
@@ -0,0 +1,70 @@
1
+ import type {EIP1193WalletProvider, EIP1193WindowWalletProvider, Methods} from 'eip-1193';
2
+ import {createCurriedJSONRPC, CurriedRPC} from 'remote-procedure-call';
3
+
4
+ const signerMethods = [
5
+ 'eth_accounts',
6
+ 'eth_sign',
7
+ 'eth_signTransaction',
8
+ 'personal_sign',
9
+ 'eth_signTypedData_v4',
10
+ 'eth_signTypedData',
11
+ ];
12
+
13
+ const connectedAccountMethods = ['eth_sendTransaction'];
14
+
15
+ const walletOnlyMethods = ['eth_requestAccounts', 'wallet_switchEthereumChain', 'wallet_addEthereumChain'];
16
+
17
+ export function createProvider(params: {
18
+ endpoint: string;
19
+ chainId: string;
20
+ prioritizeWalletProvider?: boolean;
21
+ requestsPerSecond?: number;
22
+ }): CurriedRPC<Methods> & {setWalletProvider: (walletProvider: EIP1193WindowWalletProvider | undefined) => void} & {
23
+ chainId: string;
24
+ } {
25
+ const {endpoint, chainId, prioritizeWalletProvider, requestsPerSecond} = params;
26
+ const jsonRPC = createCurriedJSONRPC(endpoint);
27
+
28
+ let walletProvider: EIP1193WindowWalletProvider | undefined;
29
+
30
+ function setWalletProvider(newWalletProvider: EIP1193WindowWalletProvider | undefined) {
31
+ walletProvider = newWalletProvider;
32
+ }
33
+
34
+ const provider = {
35
+ async request(req: {method: string; params?: any[]}) {
36
+ if (walletProvider) {
37
+ const signingMethod =
38
+ signerMethods.includes(req.method) ||
39
+ connectedAccountMethods.includes(req.method) ||
40
+ walletOnlyMethods.includes(req.method) ||
41
+ req.method.indexOf('sign') != -1;
42
+
43
+ if (prioritizeWalletProvider || signingMethod) {
44
+ const currentChainIdAsHex = await walletProvider.request({
45
+ method: 'eth_chainId',
46
+ });
47
+ const currentChainId = Number(currentChainIdAsHex).toString();
48
+ if (chainId !== currentChainId) {
49
+ if (signingMethod) {
50
+ return Promise.reject(
51
+ new Error(
52
+ `wallet provider is connected to a different chain, expected ${chainId} but got ${currentChainId}`,
53
+ ),
54
+ );
55
+ } else {
56
+ // we fallback on jsonRPc if invalid chain and not a signing method
57
+ return jsonRPC.request(req);
58
+ }
59
+ }
60
+ return walletProvider.request(req as any);
61
+ }
62
+ }
63
+
64
+ return jsonRPC.request(req);
65
+ },
66
+ } as unknown as EIP1193WalletProvider;
67
+
68
+ const curriedRPC = createCurriedJSONRPC<Methods>(provider as any, {requestsPerSecond});
69
+ return {...curriedRPC, setWalletProvider, chainId};
70
+ }