-
Notifications
You must be signed in to change notification settings - Fork 273
/
wallet.ts
889 lines (738 loc) · 25.3 KB
/
wallet.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
import { ethers } from "ethers"
import { ProgressCallback } from "ethers/lib/utils"
import { find, memoize, noop, throttle, union } from "lodash-es"
import {
Account,
DeployAccountContractTransaction,
EstimateFee,
InvocationsDetails,
KeyPair,
SignerInterface,
ec,
hash,
number,
stark,
} from "starknet"
import { Account as Accountv4 } from "starknet4"
import browser from "webextension-polyfill"
import { ArgentAccountType } from "./../shared/wallet.model"
import { getAccountEscapeFromChain } from "../shared/account/details/getAccountEscapeFromChain"
import { getAccountGuardiansFromChain } from "../shared/account/details/getAccountGuardiansFromChain"
import { getAccountTypesFromChain } from "../shared/account/details/getAccountTypesFromChain"
import {
DetailFetchers,
getAndMergeAccountDetails,
} from "../shared/account/details/getAndMergeAccountDetails"
import { withHiddenSelector } from "../shared/account/selectors"
import { getMulticallForNetwork } from "../shared/multicall"
import {
Network,
defaultNetwork,
defaultNetworks,
getProvider,
} from "../shared/network"
import { getProviderv4 } from "../shared/network/provider"
import { mapArgentAccountTypeToImplementationKey } from "../shared/network/utils"
import { cosignerSign } from "../shared/shield/backend/account"
import { ARGENT_SHIELD_ENABLED } from "../shared/shield/constants"
import { GuardianSelfSigner } from "../shared/shield/GuardianSelfSigner"
import { GuardianSignerArgentX } from "../shared/shield/GuardianSignerArgentX"
import {
IArrayStorage,
IKeyValueStorage,
IObjectStorage,
ObjectStorage,
} from "../shared/storage"
import { BaseWalletAccount, WalletAccount } from "../shared/wallet.model"
import {
accountsEqual,
baseDerivationPath,
getAccountIdentifier,
} from "../shared/wallet.service"
import { isEqualAddress } from "../ui/services/addresses"
import { LoadContracts } from "./accounts"
import {
declareContracts,
getPreDeployedAccount,
} from "./devnet/declareAccounts"
import {
getNextPathIndex,
getPathForIndex,
getStarkPair,
} from "./keys/keyDerivation"
import { getNonce, increaseStoredNonce } from "./nonce"
import backupSchema from "./schema/backup.schema"
const { calculateContractAddressFromHash, getSelectorFromName } = hash
const isDev = process.env.NODE_ENV === "development"
const isTest = process.env.NODE_ENV === "test"
const isDevOrTest = isDev || isTest
const SCRYPT_N = isDevOrTest ? 64 : 262144 // 131072 is the default value used by ethers
const CURRENT_BACKUP_VERSION = 1
export const SESSION_DURATION = isDev ? 24 * 60 * 60 : 30 * 60 // 30 mins in prod, 24 hours in dev
const CHECK_OFFSET = 10
export const PROXY_CONTRACT_CLASS_HASHES = [
"0x25ec026985a3bf9d0cc1fe17326b245dfdc3ff89b8fde106542a3ea56c5a918",
]
export const ARGENT_ACCOUNT_CONTRACT_CLASS_HASHES = [
"0x33434ad846cdd5f23eb73ff09fe6fddd568284a0fb7d1be20ee482f044dabe2",
"0x1a7820094feaf82d53f53f214b81292d717e7bb9a92bb2488092cd306f3993f",
"0x3e327de1c40540b98d05cbcb13552008e36f0ec8d61d46956d2f9752c294328",
"0x7e28fb0161d10d1cf7fe1f13e7ca57bce062731a3bd04494dfd2d0412699727",
]
export interface WalletSession {
secret: string
password: string
}
export interface WalletStorageProps {
backup?: string
selected?: BaseWalletAccount | null
discoveredOnce?: boolean
}
/*
export const walletStore = new KeyValueStorage<WalletStorageProps>(
{},
"core:wallet",
) */
export const sessionStore = new ObjectStorage<WalletSession | null>(null, {
namespace: "core:wallet:session",
areaName: "session",
})
const isNonceManagedOnAccountContract = memoize(
async (account: Accountv4, _: BaseWalletAccount) => {
try {
// This will fetch nonce from account contract instead of Starknet OS
await account.getNonce()
return true
} catch {
return false
}
},
(_, account) => {
const id = getAccountIdentifier(account)
// memoize for max 5 minutes
const timestamp = Math.floor(Date.now() / 1000 / 60 / 5)
return `${id}-${timestamp}`
},
)
export type GetNetwork = (networkId: string) => Promise<Network>
export class Wallet {
constructor(
private readonly store: IKeyValueStorage<WalletStorageProps>,
private readonly walletStore: IArrayStorage<WalletAccount>,
private readonly sessionStore: IObjectStorage<WalletSession | null>,
private readonly loadContracts: LoadContracts,
private readonly getNetwork: GetNetwork,
) {}
public async isInitialized(): Promise<boolean> {
return Boolean(await this.store.get("backup"))
}
public async isSessionOpen(): Promise<boolean> {
return (await this.sessionStore.get()) !== null
}
private async generateNewLocalSecret(
password: string,
progressCallback?: ProgressCallback,
) {
if (await this.isInitialized()) {
return
}
const ethersWallet = ethers.Wallet.createRandom()
const encryptedBackup = await ethersWallet.encrypt(
password,
{ scrypt: { N: SCRYPT_N } },
progressCallback,
)
await this.store.set("discoveredOnce", true)
await this.store.set("backup", encryptedBackup)
return this.setSession(ethersWallet.privateKey, password)
}
public async getSeedPhrase(): Promise<string> {
const session = await this.sessionStore.get()
const backup = await this.store.get("backup")
if (!(await this.isSessionOpen()) || !session || !backup) {
throw new Error("Session is not open")
}
const wallet = await ethers.Wallet.fromEncryptedJson(
backup,
session.password,
)
return wallet.mnemonic.phrase
}
public async restoreSeedPhrase(seedPhrase: string, newPassword: string) {
const session = await this.sessionStore.get()
if ((await this.isInitialized()) || session) {
throw new Error("Wallet is already initialized")
}
const ethersWallet = ethers.Wallet.fromMnemonic(seedPhrase)
const encryptedBackup = await ethersWallet.encrypt(newPassword, {
scrypt: { N: SCRYPT_N },
})
await this.importBackup(encryptedBackup)
await this.setSession(ethersWallet.privateKey, newPassword)
const accounts = await this.discoverAccounts()
if (accounts.length === 0) {
this.newAccount(defaultNetwork.id)
}
}
public async discoverAccounts() {
const session = await this.sessionStore.get()
if (!session?.secret) {
throw new Error("Wallet is not initialized")
}
const wallet = new ethers.Wallet(session?.secret)
const networks = defaultNetworks.map((network) => network.id)
const accountsResults = await Promise.all(
networks.map(async (networkId) => {
const network = await this.getNetwork(networkId)
if (!network) {
throw new Error(`Network ${networkId} not found`)
}
return this.restoreAccountsFromWallet(wallet.privateKey, network)
}),
)
const accounts = accountsResults.flatMap((x) => x)
await this.walletStore.push(accounts)
this.store.set("discoveredOnce", true)
return accounts
}
private async getAccountClassHashForNetwork(
network: Network,
accountType: ArgentAccountType,
): Promise<string> {
if (network.accountClassHash) {
return (
network.accountClassHash[
mapArgentAccountTypeToImplementationKey(accountType)
] ?? network.accountClassHash.argentAccount
)
}
const deployerAccount = await getPreDeployedAccount(network)
if (deployerAccount) {
const { accountClassHash } = await declareContracts(
network,
deployerAccount,
this.loadContracts,
)
return accountClassHash
}
return ARGENT_ACCOUNT_CONTRACT_CLASS_HASHES[0]
}
private async restoreAccountsFromWallet(
secret: string,
network: Network,
offset: number = CHECK_OFFSET,
): Promise<WalletAccount[]> {
const provider = getProvider(network)
const accounts: WalletAccount[] = []
const networkAccountClassHash = await this.getAccountClassHashForNetwork(
network,
"argent",
)
const accountClassHashes = union(ARGENT_ACCOUNT_CONTRACT_CLASS_HASHES, [
networkAccountClassHash,
])
const proxyClassHashes = PROXY_CONTRACT_CLASS_HASHES
if (!accountClassHashes?.length) {
console.error(`No known account class hashes for network ${network.id}`)
return accounts
}
const proxyClassHashAndAccountClassHash2DMap = proxyClassHashes.flatMap(
(contractHash) =>
accountClassHashes.map(
(implementation) => [contractHash, implementation] as const,
),
)
const promises = proxyClassHashAndAccountClassHash2DMap.map(
async ([contractClassHash, accountClassHash]) => {
let lastHit = 0
let lastCheck = 0
while (lastHit + offset > lastCheck) {
const starkPair = getStarkPair(lastCheck, secret, baseDerivationPath)
const starkPub = ec.getStarkKey(starkPair)
const address = calculateContractAddressFromHash(
starkPub,
contractClassHash,
stark.compileCalldata({
implementation: accountClassHash,
selector: getSelectorFromName("initialize"),
calldata: stark.compileCalldata({
signer: starkPub,
guardian: "0",
}),
}),
0,
)
const code = await provider.getCode(address)
if (code.bytecode.length > 0) {
lastHit = lastCheck
accounts.push({
address,
networkId: network.id,
network,
signer: {
type: "local_secret",
derivationPath: getPathForIndex(lastCheck, baseDerivationPath),
},
type: "argent",
needsDeploy: false, // Only deployed accounts will be recovered
})
}
++lastCheck
}
},
)
await Promise.allSettled(promises)
try {
const accountDetailFetchers: DetailFetchers[] = [getAccountTypesFromChain]
if (ARGENT_SHIELD_ENABLED) {
accountDetailFetchers.push(getAccountEscapeFromChain)
accountDetailFetchers.push(getAccountGuardiansFromChain)
}
const accountsWithDetails = await getAndMergeAccountDetails(
accounts,
accountDetailFetchers,
)
return accountsWithDetails
} catch (error) {
console.error(
"Error getting account types or guardians from chain",
error,
)
throw new Error(JSON.stringify(error, Object.getOwnPropertyNames(error)))
}
}
public async startSession(
password: string,
progressCallback?: ProgressCallback,
): Promise<boolean> {
// session has already started
const session = await this.sessionStore.get()
if (session) {
return true
}
const throttledProgressCallback = throttle(progressCallback ?? noop, 50, {
leading: true,
trailing: true,
})
// wallet is not initialized: let's initialise it
if (!(await this.isInitialized())) {
await this.generateNewLocalSecret(password, throttledProgressCallback)
return true
}
const backup = await this.store.get("backup")
if (!backup) {
throw new Error("Backup is not found")
}
try {
const wallet = await ethers.Wallet.fromEncryptedJson(
backup,
password,
throttledProgressCallback,
)
await this.setSession(wallet.privateKey, password)
// if we have not yet discovered accounts, do it now. This only applies to wallets which got restored from a backup file, as we could not restore all accounts from onchain yet as the backup was locked until now.
const discoveredOnce = await this.store.get("discoveredOnce")
if (!discoveredOnce) {
await this.discoverAccounts()
}
return true
} catch {
return false
}
}
public async checkPassword(password: string): Promise<boolean> {
const session = await this.sessionStore.get()
return session?.password === password
}
public async discoverAccountsForNetwork(
network?: Network,
offset: number = CHECK_OFFSET,
) {
const session = await this.sessionStore.get()
if (!this.isSessionOpen() || !session?.secret) {
throw new Error("Session is not open")
}
const wallet = new ethers.Wallet(session?.secret)
if (!network?.accountClassHash) {
// silent fail if no account implementation is defined for this network
return
}
const accounts = await this.restoreAccountsFromWallet(
wallet.privateKey,
network,
offset,
)
await this.walletStore.push(accounts)
}
public async newAccount(networkId: string): Promise<WalletAccount> {
const session = await this.sessionStore.get()
if (!this.isSessionOpen() || !session) {
throw Error("no open session")
}
const network = await this.getNetwork(networkId)
const accounts = await this.walletStore.get(withHiddenSelector)
const currentPaths = accounts
.filter(
(account) =>
account.signer.type === "local_secret" &&
account.network.id === networkId,
)
.map((account) => account.signer.derivationPath)
const index = getNextPathIndex(currentPaths, baseDerivationPath)
const { addressSalt, constructorCalldata } =
await this.getDeployContractPayloadForAccountIndex(index, networkId)
const proxyClassHash = PROXY_CONTRACT_CLASS_HASHES[0]
const proxyAddress = calculateContractAddressFromHash(
addressSalt,
proxyClassHash,
constructorCalldata,
0,
)
const account: WalletAccount = {
network,
networkId: network.id,
address: proxyAddress,
signer: {
type: "local_secret" as const,
derivationPath: getPathForIndex(index, baseDerivationPath),
},
type: "argent",
needsDeploy: true,
}
await this.walletStore.push([account])
await this.selectAccount(account)
return account
}
public async deployAccount(
walletAccount: WalletAccount,
transactionDetails?: InvocationsDetails | undefined,
): Promise<{ account: WalletAccount; txHash: string }> {
const starknetAccount = await this.getStarknetAccount(walletAccount)
if (!("deployAccount" in starknetAccount)) {
throw Error("Cannot deploy old accounts")
}
const deployAccountPayload = await this.getAccountDeploymentPayload(
walletAccount,
)
const { transaction_hash } = await starknetAccount.deployAccount(
deployAccountPayload,
transactionDetails,
)
await this.selectAccount(walletAccount)
return { account: walletAccount, txHash: transaction_hash }
}
public async getAccountDeploymentFee(
walletAccount: WalletAccount,
): Promise<EstimateFee> {
const starknetAccount = await this.getStarknetAccount(walletAccount)
if (!("deployAccount" in starknetAccount)) {
throw Error("Cannot estimate fee to deploy old accounts")
}
const deployAccountPayload = await this.getAccountDeploymentPayload(
walletAccount,
)
return starknetAccount.estimateAccountDeployFee(deployAccountPayload)
}
public async redeployAccount(account: WalletAccount) {
if (!this.isSessionOpen()) {
throw Error("no open session")
}
const nonce = await getNonce(account, this)
const deployTransaction = await this.deployAccount(account, { nonce })
await increaseStoredNonce(account)
return { account, txHash: deployTransaction.txHash }
}
/** Get the Account Deployment Payload
* Use it in the deployAccount and getAccountDeploymentFee methods
* @param {WalletAccount} walletAccount
*/
public async getAccountDeploymentPayload(walletAccount: WalletAccount) {
const starkPair = await this.getKeyPairByDerivationPath(
walletAccount.signer.derivationPath,
)
const starkPub = ec.getStarkKey(starkPair)
const accountClassHash = await this.getAccountClassHashForNetwork(
walletAccount.network,
"argent",
)
const constructorCallData = {
implementation: accountClassHash,
selector: getSelectorFromName("initialize"),
calldata: stark.compileCalldata({ signer: starkPub, guardian: "0" }),
}
const deployAccountPayload = {
classHash: PROXY_CONTRACT_CLASS_HASHES[0],
contractAddress: walletAccount.address,
constructorCalldata: stark.compileCalldata(constructorCallData),
addressSalt: starkPub,
}
const calculatedAccountAddress = calculateContractAddressFromHash(
deployAccountPayload.addressSalt,
deployAccountPayload.classHash,
deployAccountPayload.constructorCalldata,
0,
)
if (isEqualAddress(walletAccount.address, calculatedAccountAddress)) {
return deployAccountPayload
}
console.warn("Calculated address does not match account address")
const oldCalldata = stark.compileCalldata({
...constructorCallData,
implementation:
"0x1a7820094feaf82d53f53f214b81292d717e7bb9a92bb2488092cd306f3993f", // old implementation, ask @janek why
})
const oldCalculatedAddress = calculateContractAddressFromHash(
deployAccountPayload.addressSalt,
deployAccountPayload.classHash,
oldCalldata,
0,
)
if (isEqualAddress(oldCalculatedAddress, walletAccount.address)) {
console.warn("Address matches old implementation")
deployAccountPayload.constructorCalldata = oldCalldata
} else {
throw new Error("Calculated address does not match account address")
}
return deployAccountPayload
}
private async getDeployContractPayloadForAccountIndex(
index: number,
networkId: string,
): Promise<Omit<Required<DeployAccountContractTransaction>, "signature">> {
const hasSession = await this.isSessionOpen()
const session = await this.sessionStore.get()
const initialised = await this.isInitialized()
if (!initialised) {
throw Error("wallet is not initialized")
}
if (!hasSession || !session) {
throw Error("no open session")
}
const network = await this.getNetwork(networkId)
const starkPair = getStarkPair(index, session?.secret, baseDerivationPath)
const starkPub = ec.getStarkKey(starkPair)
const accountClassHash = await this.getAccountClassHashForNetwork(
network,
"argent",
)
const payload = {
classHash: accountClassHash,
constructorCalldata: stark.compileCalldata({
implementation: accountClassHash,
selector: getSelectorFromName("initialize"),
calldata: stark.compileCalldata({ signer: starkPub, guardian: "0" }),
}),
addressSalt: starkPub,
}
return payload
}
public async getAccount(selector: BaseWalletAccount): Promise<WalletAccount> {
const [hit] = await this.walletStore.get((account) =>
accountsEqual(account, selector),
)
if (!hit) {
throw Error("account not found")
}
return hit
}
public async getKeyPairByDerivationPath(derivationPath: string) {
const session = await this.sessionStore.get()
if (!session?.secret) {
throw Error("session is not open")
}
return getStarkPair(derivationPath, session.secret)
}
public async getSignerForAccount(
account: WalletAccount,
): Promise<KeyPair | SignerInterface> {
const keyPair = await this.getKeyPairByDerivationPath(
account.signer.derivationPath,
)
if (ARGENT_SHIELD_ENABLED && account.guardian) {
const publicKey = ec.getStarkKey(keyPair)
if (isEqualAddress(account.guardian, publicKey)) {
/** Account guardian is the same as local signer */
return new GuardianSelfSigner(keyPair)
}
return new GuardianSignerArgentX(keyPair, cosignerSign)
}
return keyPair
}
public async getStarknetAccount(
selector: BaseWalletAccount,
useLatest = false,
): Promise<Account | Accountv4> {
if (!(await this.isSessionOpen())) {
throw Error("no open session")
}
const account = await this.getAccount(selector)
if (!account) {
throw Error("account not found")
}
const provider = getProvider(
account.network && account.network.baseUrl
? account.network
: await this.getNetwork(selector.networkId),
)
const signer = await this.getSignerForAccount(account)
if (account.needsDeploy || useLatest) {
return new Account(provider, account.address, signer)
}
const providerV4 = getProviderv4(
account.network && account.network.baseUrl
? account.network
: await this.getNetwork(selector.networkId),
)
const oldAccount = new Accountv4(providerV4, account.address, signer)
const isOldAccount = await isNonceManagedOnAccountContract(
oldAccount,
account,
)
return isOldAccount
? oldAccount
: new Account(provider, account.address, signer)
}
public async getCurrentImplementation(
account: WalletAccount,
): Promise<string> {
const multicall = getMulticallForNetwork(account.network)
const [implementation] = await multicall.call({
contractAddress: account.address,
entrypoint: "get_implementation",
})
return stark.makeAddress(number.toHex(number.toBN(implementation)))
}
public async getSelectedStarknetAccount(): Promise<Account | Accountv4> {
if (!this.isSessionOpen()) {
throw Error("no open session")
}
const account = await this.getSelectedAccount()
if (!account) {
throw new Error("no selected account")
}
return this.getStarknetAccount(account)
}
public async getSelectedAccount(): Promise<WalletAccount | undefined> {
if (!this.isSessionOpen()) {
return
}
const accounts = await this.walletStore.get()
const selectedAccount = await this.store.get("selected")
const defaultAccount =
accounts.find((account) => account.networkId === defaultNetwork.id) ??
accounts[0]
if (!selectedAccount) {
return defaultAccount
}
const account = find(accounts, (account) =>
accountsEqual(selectedAccount, account),
)
return account ?? defaultAccount
}
public async selectAccount(accountIdentifier?: BaseWalletAccount) {
if (!accountIdentifier) {
await this.store.set("selected", null) // Set null instead of undefinded
return
}
const accounts = await this.walletStore.get()
const account = find(accounts, (account) =>
accountsEqual(account, accountIdentifier),
)
if (!account) {
throw Error("account not found")
}
const { address, networkId } = account // makes sure to strip away unused properties
await this.store.set("selected", { address, networkId })
return account
}
public async lock() {
await this.sessionStore.set(this.sessionStore.defaults)
}
public async exportBackup(): Promise<{ url: string; filename: string }> {
const backup = await this.store.get("backup")
if (!backup) {
throw Error("no local backup")
}
const blob = new Blob([backup], {
type: "application/json",
})
const url = URL.createObjectURL(blob)
const filename = "argent-x-backup.json"
return { url, filename }
}
public async getPublicKey(baseAccount?: BaseWalletAccount): Promise<string> {
const account = baseAccount
? await this.getAccount(baseAccount)
: await this.getSelectedAccount()
if (!account) {
throw new Error("no selected account")
}
const starkPair = await this.getKeyPairByDerivationPath(
account.signer.derivationPath,
)
const starkPub = ec.getStarkKey(starkPair)
return starkPub
}
public async exportPrivateKey(
baseWalletAccount: BaseWalletAccount,
): Promise<string> {
const session = await this.sessionStore.get()
if (!this.isSessionOpen() || !session?.secret) {
throw new Error("Session is not open")
}
const account = await this.getAccount(baseWalletAccount)
if (!account) {
throw new Error("no selected account")
}
const starkPair = getStarkPair(
account.signer.derivationPath,
session.secret,
)
return starkPair.getPrivate().toString()
}
public static validateBackup(backupString: string): boolean {
try {
const backup = JSON.parse(backupString)
return backupSchema.isValidSync(backup)
} catch {
return false
}
}
private async setSession(secret: string, password: string) {
await this.sessionStore.set({ secret, password })
browser.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === "session_timeout") {
return this.lock()
}
})
const alarm = await browser.alarms.get("session_timeout")
if (alarm?.name !== "session_timeout") {
browser.alarms.create("session_timeout", {
delayInMinutes: SESSION_DURATION,
})
}
}
public async importBackup(backup: string): Promise<void> {
if (!Wallet.validateBackup(backup)) {
throw new Error("invalid backup file in local storage")
}
const backupJson = JSON.parse(backup)
if (backupJson.argent?.version !== CURRENT_BACKUP_VERSION) {
// in the future, backup file migration will happen here
}
await this.store.set("backup", backup)
const accounts: WalletAccount[] = await Promise.all(
(backupJson.argent?.accounts ?? []).map(async (account: any) => {
const network = await this.getNetwork(account.network)
return {
...account,
network,
networkId: network.id,
}
}),
)
if (accounts.length > 0) {
await this.walletStore.push(accounts)
}
}
}