forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolana.ts
More file actions
265 lines (242 loc) · 6.78 KB
/
Copy pathsolana.ts
File metadata and controls
265 lines (242 loc) · 6.78 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import type {
ConnectedWallet,
WalletChainInfo,
WalletId
} from './types';
export type SolanaNetworkName =
| 'mainnet-beta'
| 'testnet'
| 'devnet';
const CONNECT_TIMEOUT_MS = 30_000;
const SOLANA_WALLET_META: Partial<
Record<
WalletId,
{ name: string; connectorName: string }
>
> = {
'phantom-solana': {
name: 'Phantom',
connectorName: 'Phantom'
},
solflare: {
name: 'Solflare',
connectorName: 'Solflare'
},
backpack: {
name: 'Backpack',
connectorName: 'Backpack'
}
};
const solanaNetwork =
process.env.NEXT_PUBLIC_SOLANA_NETWORK === 'devnet'
? 'devnet'
: process.env.NEXT_PUBLIC_SOLANA_NETWORK === 'testnet'
? 'testnet'
: 'mainnet-beta';
const SOLANA_NETWORKS: Record<
SolanaNetworkName,
{
chain: WalletChainInfo;
rpcUrl: string;
}
> = {
'mainnet-beta': {
chain: {
id: 'solana:mainnet-beta',
family: 'solana',
name: 'Solana',
network: 'mainnet-beta',
isSupported: true
},
rpcUrl: 'https://api.mainnet-beta.solana.com'
},
testnet: {
chain: {
id: 'solana:testnet',
family: 'solana',
name: 'Solana Testnet',
network: 'testnet',
isSupported: true
},
rpcUrl: 'https://api.testnet.solana.com'
},
devnet: {
chain: {
id: 'solana:devnet',
family: 'solana',
name: 'Solana Devnet',
network: 'devnet',
isSupported: true
},
rpcUrl: 'https://api.devnet.solana.com'
}
};
const getChainConfig = () => SOLANA_NETWORKS[solanaNetwork];
const buildWallet = (
walletId: WalletId,
address: string
): ConnectedWallet => {
const meta = SOLANA_WALLET_META[walletId] ?? {
name: String(walletId),
connectorName: String(walletId)
};
return {
id: walletId,
name: meta.name,
address,
family: 'solana',
chain: getChainConfig().chain,
connectorName: meta.connectorName,
connectedAt: Date.now()
};
};
const getBrowserWindow = () =>
typeof window !== 'undefined' ? window : undefined;
type SolanaProviderApi = {
publicKey?: { toString: () => string } | null;
connect: (opts?: { onlyIfTrusted?: boolean }) => Promise<{ publicKey: { toString: () => string } }>;
disconnect: () => Promise<void>;
isConnected?: boolean;
};
const withTimeout = async <T>(
promise: Promise<T>,
label: string,
ms = CONNECT_TIMEOUT_MS
): Promise<T> => {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<T>((_, reject) => {
timer = setTimeout(() => {
reject(
new Error(
`${label} timed out after ${Math.round(ms / 1000)}s. Check the extension popup or try again.`
)
);
}, ms);
})
]);
} finally {
if (timer) clearTimeout(timer);
}
};
const getPhantomProvider = (): SolanaProviderApi | undefined => {
const w = getBrowserWindow() as any;
if (w?.phantom?.solana?.isPhantom) {
return w.phantom.solana;
}
return undefined;
};
const getSolflareProvider = (): SolanaProviderApi | undefined => {
const w = getBrowserWindow() as any;
if (w?.solflare?.isSolflare) {
return w.solflare;
}
return undefined;
};
const getBackpackProvider = (): SolanaProviderApi | undefined => {
const w = getBrowserWindow() as any;
if (w?.backpack) {
return w.backpack;
}
return undefined;
};
const connectProvider = async (
provider: SolanaProviderApi | undefined,
walletId: WalletId,
name: string
): Promise<ConnectedWallet> => {
if (!provider) {
throw new Error(`${name} is not installed.`);
}
try {
const response = await withTimeout(
provider.connect(),
name
);
const address = response.publicKey.toString();
if (!address) {
throw new Error(`${name} did not return a public key.`);
}
return buildWallet(walletId, address);
} catch (err: any) {
throw new Error(err?.message || `${name} connection failed.`);
}
};
const restoreProvider = async (
provider: SolanaProviderApi | undefined,
walletId: WalletId,
name: string
): Promise<ConnectedWallet | null> => {
if (!provider) return null;
try {
const response = await withTimeout(
provider.connect({ onlyIfTrusted: true }),
`${name} restore`,
5000
);
const address = response.publicKey.toString();
return address ? buildWallet(walletId, address) : null;
} catch {
return null;
}
};
export const detectSolanaWallets = async () => {
return {
'phantom-solana': Boolean(getPhantomProvider()),
solflare: Boolean(getSolflareProvider()),
backpack: Boolean(getBackpackProvider())
};
};
export const connectSolanaWallet = async (
walletId: WalletId
): Promise<ConnectedWallet> => {
switch (walletId) {
case 'phantom-solana':
return connectProvider(getPhantomProvider(), walletId, 'Phantom');
case 'solflare':
return connectProvider(getSolflareProvider(), walletId, 'Solflare');
case 'backpack':
return connectProvider(getBackpackProvider(), walletId, 'Backpack');
default:
throw new Error(`Solana wallet "${walletId}" is not supported.`);
}
};
export const restoreSolanaWallet = async (
walletId: WalletId
): Promise<ConnectedWallet | null> => {
switch (walletId) {
case 'phantom-solana':
return restoreProvider(getPhantomProvider(), walletId, 'Phantom');
case 'solflare':
return restoreProvider(getSolflareProvider(), walletId, 'Solflare');
case 'backpack':
return restoreProvider(getBackpackProvider(), walletId, 'Backpack');
default:
return null;
}
};
export const disconnectSolanaWallet = async (
walletId: WalletId
): Promise<void> => {
let provider: SolanaProviderApi | undefined;
switch (walletId) {
case 'phantom-solana':
provider = getPhantomProvider();
break;
case 'solflare':
provider = getSolflareProvider();
break;
case 'backpack':
provider = getBackpackProvider();
break;
}
if (provider && provider.disconnect) {
try {
await provider.disconnect();
} catch {
// ignore
}
}
};