-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathuseDerivationAccounts.ts
202 lines (185 loc) · 6.15 KB
/
useDerivationAccounts.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
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
import { Keypair as HeliumKeypair, Mnemonic } from '@helium/crypto'
import { Asset, truthy } from '@helium/spl-utils'
import {
AccountInfo,
Keypair,
PublicKey,
RpcResponseAndContext,
} from '@solana/web3.js'
import axios from 'axios'
import * as bip39 from 'bip39'
import { Buffer } from 'buffer'
import * as ed25519 from 'ed25519-hd-key'
import { useEffect, useMemo, useState } from 'react'
import Config from 'react-native-config'
import { retryWithBackoff } from '@utils/retryWithBackoff'
import { useSolana } from '@features/solana/SolanaProvider'
export const solanaDerivation = (account = -1, change: number | undefined) => {
if (account === -1) {
return "m/44'/501'" // main derivation path
}
if (typeof change !== 'undefined') {
return `m/44'/501'/${account}'/${change}'` // sub derivation path
}
return `m/44'/501'/${account}'` // sub derivation path
}
const heliumDerivation = (account = -1) => {
if (account === -1) {
return "m/44'/904'" // main derivation path
}
return `m/44'/904'/${account}'/0'` // sub derivation path
}
export async function keypairFromSeed(
seed: Buffer,
derivationPath: string,
): Promise<Keypair | null> {
try {
const derivedSeed = ed25519.derivePath(
derivationPath,
seed.toString('hex'),
).key
return Keypair.fromSeed(derivedSeed)
} catch (e) {
console.error(`Error deriving keypair at ${derivationPath}`, e)
return null
}
}
export type ResolvedPath = {
derivationPath: string
keypair: Keypair
balance?: number
tokens?: RpcResponseAndContext<
Array<{
pubkey: PublicKey
account: AccountInfo<Buffer>
}>
>
nfts?: Asset[]
needsMigrated?: boolean
}
export const HELIUM_DERIVATION = 'Helium L1'
export const MAIN_DERIVATION_PATHS = [
HELIUM_DERIVATION,
heliumDerivation(-1),
solanaDerivation(-1, undefined),
]
export const useDerivationAccounts = ({ mnemonic }: { mnemonic?: string }) => {
const { connection } = useSolana()
const [resolvedGroups, setResolvedGroups] = useState<ResolvedPath[][]>([])
const [error, setError] = useState<Error | null>(null)
const [loading, setLoading] = useState(false)
const derivationAccounts = useMemo(
() => resolvedGroups.flat(),
[resolvedGroups],
)
const solanaWithChange = (start: number, end: number) =>
new Array(end - start).fill(0).map((_, i) => solanaDerivation(i + start, 0))
const solanaWithoutChange = (start: number, end: number) =>
new Array(end - start)
.fill(0)
.map((_, i) => solanaDerivation(i + start, undefined))
const [groups, setGroups] = useState([
[
...MAIN_DERIVATION_PATHS,
...solanaWithChange(0, 10),
...solanaWithoutChange(0, 10),
],
])
// When mnemonic changes, reset resolved groups
useEffect(() => {
setResolvedGroups([])
}, [mnemonic])
const seed = useMemo(() => {
if (mnemonic) {
return bip39.mnemonicToSeedSync(mnemonic, '')
}
}, [mnemonic])
useEffect(() => {
if (seed && groups.some((_, i) => !resolvedGroups[i])) {
;(async () => {
setLoading(true)
try {
if (!connection) return
const resolved = await Promise.all(
groups.map(async (group, index) => {
if (resolvedGroups[index]) return resolvedGroups[index]
return (
await Promise.all(
group.map(async (derivationPath) => {
const keypair =
derivationPath === HELIUM_DERIVATION
? Keypair.fromSecretKey(
(
await HeliumKeypair.fromMnemonic(
new Mnemonic(mnemonic?.split(' ') || []),
)
).privateKey,
)
: await keypairFromSeed(seed, derivationPath)
if (keypair) {
let needsMigrated = false
const [balance] = await Promise.all([
retryWithBackoff(() =>
connection.getBalance(keypair.publicKey),
),
// retryWithBackoff(() =>
// connection.getTokenAccountsByOwner(
// keypair.publicKey,
// {
// programId: TOKEN_PROGRAM_ID,
// },
// ),
// ),
// retryWithBackoff(() =>
// getAssetsByOwner(
// connection.rpcEndpoint,
// keypair.publicKey.toBase58(),
// {
// limit: 10,
// },
// ),
// ),
])
if (derivationPath === heliumDerivation(-1)) {
const url = `${
Config.MIGRATION_SERVER_URL
}/migrate/${keypair.publicKey.toBase58()}`
// eslint-disable-next-line no-await-in-loop
const { transactions } = (await axios.get(url)).data
needsMigrated = transactions.length > 0
}
return {
derivationPath,
keypair,
balance,
needsMigrated,
} as ResolvedPath
}
}),
)
).filter(truthy)
}),
)
setResolvedGroups(resolved)
} catch (e: any) {
setError(e)
} finally {
setLoading(false)
}
})()
}
}, [seed, groups, connection, resolvedGroups, mnemonic])
return {
error,
loading,
derivationAccounts,
fetchMore: () =>
setGroups([
...groups,
[
...solanaWithChange(groups.length * 10, groups.length * 10 + 10),
...solanaWithoutChange(groups.length * 10, groups.length * 10 + 10),
],
]),
}
}