-
Notifications
You must be signed in to change notification settings - Fork 117
/
connector.ts
59 lines (48 loc) · 1.64 KB
/
connector.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
import { AbstractConnector } from '@web3-react/abstract-connector';
import { ConnectorUpdate } from '@web3-react/types';
import SafeAppsSDK, { SafeInfo } from '@gnosis.pm/safe-apps-sdk';
import { SafeAppProvider } from '@gnosis.pm/safe-apps-provider';
class SafeAppConnector extends AbstractConnector {
private readonly sdk = new SafeAppsSDK();
private safe: SafeInfo | undefined;
private provider: SafeAppProvider | undefined;
async activate(): Promise<ConnectorUpdate> {
const runningAsSafeApp = await this.isSafeApp();
if (!runningAsSafeApp) {
throw new Error('The app is loaded outside safe context');
}
return { provider: await this.getProvider(), chainId: await this.getChainId(), account: await this.getAccount() };
}
public async getSafeInfo(): Promise<SafeInfo> {
if (!this.safe) {
this.safe = await this.sdk.safe.getInfo();
}
return this.safe;
}
public async getProvider(): Promise<SafeAppProvider> {
if (!this.provider) {
const safe = await this.getSafeInfo();
this.provider = new SafeAppProvider(safe, this.sdk);
}
return this.provider;
}
public async getChainId(): Promise<number> {
const provider = await this.getProvider();
return provider.chainId;
}
public async getAccount(): Promise<string> {
const safe = await this.getSafeInfo();
return safe.safeAddress;
}
public deactivate(): void {
return;
}
public async isSafeApp(): Promise<boolean> {
const safe = await Promise.race([
this.getSafeInfo(),
new Promise<undefined>((resolve) => setTimeout(resolve, 300)),
]);
return !!safe;
}
}
export { SafeAppConnector };