-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.ts
177 lines (152 loc) · 5.59 KB
/
index.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
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
175
176
177
import { ChainNotConfiguredError, createConnector } from 'wagmi';
import {
getAddress,
UserRejectedRequestError,
numberToHex,
ProviderRpcError,
SwitchChainError
} from 'viem';
import { WalletMobileSDKEVMProvider, configure } from '@coinbase/wallet-mobile-sdk';
import type { WalletMobileSDKProviderOptions } from '@coinbase/wallet-mobile-sdk/build/WalletMobileSDKEVMProvider';
import { ConstantsUtil, PresetsUtil } from '@reown/appkit-common-react-native';
type CoinbaseConnectorParameters = WalletMobileSDKProviderOptions & {
redirect: string;
};
type Provider = WalletMobileSDKEVMProvider;
coinbaseConnector.type = PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID]!;
export function coinbaseConnector(parameters: CoinbaseConnectorParameters) {
let _provider: Provider;
return createConnector<Provider>(config => ({
id: ConstantsUtil.COINBASE_CONNECTOR_ID,
name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.COINBASE_CONNECTOR_ID]!,
type: coinbaseConnector.type,
async connect({ chainId } = {}) {
try {
const provider = await this.getProvider();
let accounts;
const isConnected = provider.connected;
if (!isConnected) {
accounts = (
(await provider.request({
method: 'eth_requestAccounts'
})) as string[]
).map(getAddress);
} else {
accounts = provider.selectedAddress ? [getAddress(provider.selectedAddress)] : [];
}
provider.on('accountsChanged', this.onAccountsChanged);
provider.on('chainChanged', this.onChainChanged);
provider.on('disconnect', this.onDisconnect.bind(this));
// Switch to chain if provided
let currentChainId = await this.getChainId();
if (chainId && currentChainId !== chainId) {
const chain = await this.switchChain!({ chainId }).catch(() => ({
id: currentChainId
}));
currentChainId = chain?.id ?? currentChainId;
}
return { accounts, chainId: currentChainId };
} catch (error) {
if (/(Error error 0|User rejected the request)/i.test((error as Error).message))
throw new UserRejectedRequestError(error as Error);
if (/(Error error 5|Could not open wallet)/i.test((error as Error).message))
throw new Error(`Wallet not found. SDK Error: ${(error as Error).message}`);
throw error;
}
},
async disconnect() {
const provider = await this.getProvider();
provider.removeListener('accountsChanged', this.onAccountsChanged);
provider.removeListener('chainChanged', this.onChainChanged);
provider.removeListener('disconnect', this.onDisconnect.bind(this));
provider.disconnect();
},
async getAccounts() {
const provider = await this.getProvider();
return (
await provider.request<string[]>({
method: 'eth_accounts'
})
).map(getAddress);
},
async getChainId() {
const provider = await this.getProvider();
return Number(provider.chainId);
},
async getProvider({ chainId } = {}) {
function initProvider() {
configure({
callbackURL: new URL(parameters.redirect),
hostURL: new URL('https://wallet.coinbase.com/wsegue'),
hostPackageName: 'org.toshi'
});
return new WalletMobileSDKEVMProvider({ ...parameters });
}
if (!_provider) {
_provider = initProvider();
}
if (chainId) {
await this.switchChain?.({ chainId });
}
return _provider;
},
async isAuthorized() {
try {
const accounts = await this.getAccounts();
return !!accounts.length;
} catch {
return false;
}
},
async switchChain({ chainId }) {
const chain = config.chains.find(c => c.id === chainId);
if (!chain) throw new SwitchChainError(new ChainNotConfiguredError());
const provider = await this.getProvider();
const chainId_ = numberToHex(chain.id);
try {
await provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: chainId_ }]
});
return chain;
} catch (error) {
// Indicates chain is not added to provider
if ((error as ProviderRpcError).code === 4902) {
try {
await provider.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: chainId_,
chainName: chain.name,
nativeCurrency: chain.nativeCurrency,
rpcUrls: [chain.rpcUrls.default?.http[0] ?? ''],
blockExplorerUrls: [chain.blockExplorers?.default.url]
}
]
});
return chain;
} catch (e) {
throw new UserRejectedRequestError(e as Error);
}
}
throw new SwitchChainError(error as Error);
}
},
onAccountsChanged(accounts) {
if (accounts.length === 0) config.emitter.emit('disconnect');
else config.emitter.emit('change', { accounts: accounts.map(getAddress) });
},
onChainChanged(chain) {
const chainId = Number(chain);
config.emitter.emit('change', { chainId });
},
async onDisconnect(_error) {
config.emitter.emit('disconnect');
const provider = await this.getProvider();
provider.removeListener('accountsChanged', this.onAccountsChanged);
provider.removeListener('chainChanged', this.onChainChanged);
provider.removeListener('disconnect', this.onDisconnect.bind(this));
}
}));
}