-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathswitch-ethereum-chain.js
163 lines (143 loc) · 4.33 KB
/
switch-ethereum-chain.js
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
import { ethErrors } from 'eth-rpc-errors';
import { omit } from 'lodash';
import { ApprovalType } from '@metamask/controller-utils';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import {
CHAIN_ID_TO_TYPE_MAP,
NETWORK_TO_NAME_MAP,
CHAIN_ID_TO_RPC_URL_MAP,
CURRENCY_SYMBOLS,
BUILT_IN_INFURA_NETWORKS,
} from '../../../../../shared/constants/network';
import {
isPrefixedFormattedHexString,
isSafeChainId,
} from '../../../../../shared/modules/network.utils';
const switchEthereumChain = {
methodNames: [MESSAGE_TYPE.SWITCH_ETHEREUM_CHAIN],
implementation: switchEthereumChainHandler,
hookNames: {
getCurrentChainId: true,
findNetworkConfigurationBy: true,
findNetworkClientIdByChainId: true,
setNetworkClientIdForDomain: true,
setProviderType: true,
setActiveNetwork: true,
requestUserApproval: true,
getNetworkConfigurations: true,
getNetworkClientIdForDomain: true,
getProviderConfig: true,
},
};
export default switchEthereumChain;
function findExistingNetwork(chainId, findNetworkConfigurationBy) {
if (
Object.values(BUILT_IN_INFURA_NETWORKS)
.map(({ chainId: id }) => id)
.includes(chainId)
) {
return {
chainId,
ticker: CURRENCY_SYMBOLS.ETH,
nickname: NETWORK_TO_NAME_MAP[chainId],
rpcUrl: CHAIN_ID_TO_RPC_URL_MAP[chainId],
type: CHAIN_ID_TO_TYPE_MAP[chainId],
};
}
return findNetworkConfigurationBy({ chainId });
}
async function switchEthereumChainHandler(
req,
res,
_next,
end,
{
getCurrentChainId,
findNetworkConfigurationBy,
findNetworkClientIdByChainId,
setNetworkClientIdForDomain,
setProviderType,
setActiveNetwork,
requestUserApproval,
getProviderConfig,
},
) {
if (!req.params?.[0] || typeof req.params[0] !== 'object') {
return end(
ethErrors.rpc.invalidParams({
message: `Expected single, object parameter. Received:\n${JSON.stringify(
req.params,
)}`,
}),
);
}
const { origin } = req;
const { chainId } = req.params[0];
const otherKeys = Object.keys(omit(req.params[0], ['chainId']));
if (otherKeys.length > 0) {
return end(
ethErrors.rpc.invalidParams({
message: `Received unexpected keys on object parameter. Unsupported keys:\n${otherKeys}`,
}),
);
}
const _chainId = typeof chainId === 'string' && chainId.toLowerCase();
if (!isPrefixedFormattedHexString(_chainId)) {
return end(
ethErrors.rpc.invalidParams({
message: `Expected 0x-prefixed, unpadded, non-zero hexadecimal string 'chainId'. Received:\n${chainId}`,
}),
);
}
if (!isSafeChainId(parseInt(_chainId, 16))) {
return end(
ethErrors.rpc.invalidParams({
message: `Invalid chain ID "${_chainId}": numerical value greater than max safe value. Received:\n${chainId}`,
}),
);
}
const requestData = {
toNetworkConfiguration: findExistingNetwork(
_chainId,
findNetworkConfigurationBy,
),
};
requestData.fromNetworkConfiguration = getProviderConfig();
if (requestData.toNetworkConfiguration) {
const currentChainId = getCurrentChainId();
// we might want to change all this so that it displays the network you are switching from -> to (in a way that is domain - specific)
const networkClientId = findNetworkClientIdByChainId(_chainId);
if (currentChainId === _chainId) {
setNetworkClientIdForDomain(req.origin, networkClientId);
res.result = null;
return end();
}
try {
const approvedRequestData = await requestUserApproval({
origin,
type: ApprovalType.SwitchEthereumChain,
requestData,
});
if (
Object.values(BUILT_IN_INFURA_NETWORKS)
.map(({ chainId: id }) => id)
.includes(_chainId)
) {
await setProviderType(approvedRequestData.type);
} else {
await setActiveNetwork(approvedRequestData.id);
}
setNetworkClientIdForDomain(req.origin, networkClientId);
res.result = null;
} catch (error) {
return end(error);
}
return end();
}
return end(
ethErrors.provider.custom({
code: 4902, // To-be-standardized "unrecognized chain ID" error
message: `Unrecognized chain ID "${chainId}". Try adding the chain using ${MESSAGE_TYPE.ADD_ETHEREUM_CHAIN} first.`,
}),
);
}