-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathindex.ts
More file actions
174 lines (145 loc) · 5.33 KB
/
index.ts
File metadata and controls
174 lines (145 loc) · 5.33 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
import { Connector } from "@web3-react/types";
import { LedgerConstructorArgs, LedgerOptions, LedgerProvider } from "./type";
export const URI_AVAILABLE = "URI_AVAILABLE";
function parseChainId(chainId: string | number) {
return typeof chainId === "string" ? Number.parseInt(chainId, 16) : chainId;
}
const isLogActive = false;
export class Ledger extends Connector {
private readonly defaultChainId: number = 1;
private readonly options: LedgerOptions;
private connectKit?: any;
public provider?: LedgerProvider;
constructor({ actions, options, onError }: LedgerConstructorArgs) {
isLogActive && console.log("Ledger Connector Constructor: Initializing...");
super(actions, onError);
this.options = options;
}
private chainChangedListener = (chainId: string): void => {
isLogActive &&
console.log("chainChangedListener: Handling chain changed event...");
this.actions.update({ chainId: Number.parseInt(chainId, 16) });
};
private accountsChangedListener = (accounts: string[]): void => {
isLogActive &&
console.log(
"accountsChangedListener: Handling accounts changed event..."
);
this.actions.update({ accounts });
};
private async isomorphicInitialize() {
console.group("isomorphicInitialize method");
isLogActive && console.log("isomorphicInitialize: Loading provider...");
try {
if (this.provider) return this.provider;
this.connectKit = require('@ledgerhq/connect-kit');
const {
projectId,
chains,
optionalChains,
requiredMethods,
optionalMethods,
requiredEvents,
optionalEvents,
rpcMap = {
1: "https://cloudflare-eth.com/", // Mainnet
5: "https://goerli.optimism.io/", // Goerli
137: "https://polygon-rpc.com/", // Polygon
},
} = this.options;
this.connectKit.checkSupport({
providerType: "Ethereum",
walletConnectVersion: 2,
projectId,
chains,
optionalChains,
methods: requiredMethods,
optionalMethods,
events: requiredEvents,
optionalEvents,
rpcMap,
});
this.connectKit.enableDebugLogs();
const provider: LedgerProvider = (this.provider =
(await this.connectKit.getProvider()) as LedgerProvider);
provider.on("chainChanged", this.chainChangedListener);
provider.on("accountsChanged", this.accountsChangedListener);
return provider;
} finally {
console.groupEnd();
}
}
async connectEagerly() {
isLogActive && console.log("connectEagerly: Connecting eagerly...");
try {
this.provider = await this.isomorphicInitialize();
if (!this.provider.session) {
throw new Error("No active session found. Connect your wallet first.");
}
const [chainId, accounts] = await Promise.all([
this.provider.request({ method: "eth_chainId" }) as Promise<string>,
this.provider.request({ method: "eth_accounts" }) as Promise<string[]>,
]);
this.actions.update({ chainId: parseChainId(chainId), accounts });
} catch (error) {
console.debug("connectEagerly: Could not connect eagerly", error);
await this.deactivate();
}
}
public async activate(
desiredChainId: number = this.defaultChainId
): Promise<void> {
console.group("activate method");
isLogActive && console.group("activate: Activating...");
try {
this.provider = await this.isomorphicInitialize();
const { request }: { request: any } = this.provider;
if (this.provider.accounts?.length === 0) {
const accounts = (await request({
method: "eth_requestAccounts",
})) as string[];
const chainId = (await request({
method: "eth_chainId",
})) as string;
this.actions.update({ chainId: parseChainId(chainId), accounts });
return;
}
if (desiredChainId === this.provider.chainId) return;
const isConnectedToDesiredChain =
this.provider.session?.namespaces?.eip155.accounts.some(
(account: string) => account.startsWith(`eip155:${desiredChainId}:`)
);
if (!isConnectedToDesiredChain) {
if (this.options.optionalChains?.includes(desiredChainId)) {
throw new Error(
`Cannot activate an optional chain (${desiredChainId}), as the wallet is not connected to it.\n\tYou should handle this error in application code, as there is no guarantee that a wallet is connected to a chain configured in "optionalChains".`
);
}
throw new Error(
`Unknown chain (${desiredChainId}). Make sure to include any chains you might connect to in the "chains" or "optionalChains" parameters when initializing WalletConnect.`
);
}
await request({
method: "wallet_switchEthereumChain",
params: [{ chainId: "0x" + desiredChainId.toString(16) }],
});
this.actions.update({
chainId: desiredChainId,
accounts: this.provider.accounts,
});
} catch (error) {
await this.deactivate();
throw error;
} finally {
console.groupEnd();
}
}
async deactivate() {
isLogActive && console.log("deactivate: Deactivating...");
if (this.provider) {
this.provider?.disconnect?.();
this.provider = undefined;
}
this.actions.resetState();
}
}