add multi-wallet EVM support with evm_wallets DB table

This commit is contained in:
2026-05-20 20:26:40 +08:00
parent c55a33e9ab
commit d4b989c191
5 changed files with 319 additions and 77 deletions
+67 -2
View File
@@ -16,6 +16,7 @@ import {
getTransactionDetails,
} from './lib/transactions'
import { migrate } from 'drizzle-orm/bun-sqlite/migrator'
import { eq } from 'drizzle-orm'
import { db } from './lib/db'
import { join } from 'path'
import { getENV } from './lib/get-env'
@@ -34,6 +35,7 @@ import {
transactions,
transactionReceipts,
txHistory,
evmWallets,
} from './lib/db/schema'
const env = getENV()
@@ -265,6 +267,22 @@ type RPC = {
connected: boolean
}
}
evmCreateWallet: {
params: { name: string; phrase: string; passwordHash?: string }
response: { id: string; name: string; createdAt: string }
}
evmListWallets: {
params: {}
response: Array<{ id: string; name: string; hasPassword: boolean; vaultKey: string; createdAt: string }>
}
evmGetSeed: {
params: { vaultKey: string }
response: string
}
evmDeleteWallet: {
params: { id: string }
response: void
}
}
messages: {}
}>
@@ -379,15 +397,19 @@ const rpc = BrowserView.defineRPC<RPC>({
requests: {
resetApp: async () => {
try {
const wallets = db.select().from(evmWallets).all()
await Promise.all([
Bun.secrets.delete({ service: 'koins', name: 'vault' }),
Bun.secrets.delete({ service: 'koins', name: 'vault_password' }),
Bun.secrets.delete({ service: 'koins', name: 'alchemy_key' }),
...wallets.flatMap((w) => [
Bun.secrets.delete({ service: 'koins', name: w.vaultKey }),
Bun.secrets.delete({ service: 'koins', name: `evm_auth_${w.id}` }),
]),
])
sqlite.run('DELETE FROM token_metadata')
sqlite.run('DELETE FROM transactions')
sqlite.run('DELETE FROM transaction_receipts')
sqlite.run('DELETE FROM tx_history')
sqlite.run('DELETE FROM evm_wallets')
console.log('[rpc] resetApp complete')
return true
} catch (e) {
@@ -749,6 +771,49 @@ const rpc = BrowserView.defineRPC<RPC>({
)
return wallets
},
evmCreateWallet: async ({ name, phrase, passwordHash }) => {
console.log('[rpc] evmCreateWallet:', name)
const id = crypto.randomUUID()
const vaultKey = `evm_seed_${id}`
await Bun.secrets.set({ service: 'koins', name: vaultKey, value: phrase })
await db.insert(evmWallets).values({
id,
name,
passwordHash: passwordHash ?? null,
vaultKey,
createdAt: new Date().toISOString(),
})
console.log('[rpc] evmCreateWallet complete:', id)
return { id, name, createdAt: new Date().toISOString() }
},
evmListWallets: async () => {
console.log('[rpc] evmListWallets')
const wallets = db.select().from(evmWallets).all()
return wallets.map((w) => ({
id: w.id,
name: w.name,
hasPassword: !!w.passwordHash,
vaultKey: w.vaultKey,
createdAt: w.createdAt,
}))
},
evmGetSeed: async ({ vaultKey }) => {
console.log('[rpc] evmGetSeed:', vaultKey)
const seed = await Bun.secrets.get({ service: 'koins', name: vaultKey })
if (!seed) throw new Error('Seed not found in keychain')
return seed
},
evmDeleteWallet: async ({ id }) => {
console.log('[rpc] evmDeleteWallet:', id)
const wallet = db.select().from(evmWallets).where(eq(evmWallets.id, id)).get()
if (!wallet) throw new Error('Wallet not found')
await Promise.all([
Bun.secrets.delete({ service: 'koins', name: wallet.vaultKey }),
Bun.secrets.delete({ service: 'koins', name: `evm_auth_${id}` }),
])
db.delete(evmWallets).where(eq(evmWallets.id, id)).run()
console.log('[rpc] evmDeleteWallet complete')
},
},
messages: {},
},
+8
View File
@@ -72,6 +72,14 @@ export const transactionReceipts = sqliteTable(
}),
)
export const evmWallets = sqliteTable('evm_wallets', {
id: text('id').primaryKey(),
name: text('name').notNull(),
passwordHash: text('password_hash'),
vaultKey: text('vault_key').notNull(),
createdAt: text('created_at').notNull(),
})
export const txHistory = sqliteTable(
'tx_history',
{
@@ -19,6 +19,10 @@
import QrCodeIcon from '@lucide/svelte/icons/qr-code'
import SettingsIcon from '@lucide/svelte/icons/settings'
import Fingerprint from '@lucide/svelte/icons/fingerprint'
import Trash2 from '@lucide/svelte/icons/trash-2'
import Plus from '@lucide/svelte/icons/plus'
import WalletIcon from '@lucide/svelte/icons/wallet'
import LockKeyhole from '@lucide/svelte/icons/lock-keyhole'
import * as Dialog from '$lib/components/ui/dialog/index.js'
import QRCode from 'qrcode'
import Loader from './loader.svelte'
@@ -57,9 +61,11 @@
let inputSeed = $state('')
let inputPassword = $state('')
let inputUnlockPassword = $state('')
let inputWalletName = $state('')
let apiKeyInput = $state('')
let qrDataUrl = $state('')
let qrDialogOpen = $state(false)
let showCreateForm = $state(false)
$effect(() => {
if (w.address) {
QRCode.toDataURL(w.address, { width: 256, margin: 1 }).then(
@@ -91,43 +97,100 @@
class="mx-auto mt-16 max-w-md text-center text-muted-foreground text-sm">
Loading...
</div>
{:else if !w.vaultExists}
{:else if w.wallets.length === 0 || showCreateForm}
<Card>
<CardHeader>
<CardTitle>Import Wallet</CardTitle>
<CardTitle>
{#if showCreateForm}
{@const cur = w.currentWallet}
{cur ? `Add Another Wallet` : `Import Wallet`}
{:else}
Import Wallet
{/if}
</CardTitle>
<CardDescription>
Enter your seed phrase to save it securely in your system
keychain
Name your wallet and enter your seed phrase to save it securely
</CardDescription>
</CardHeader>
<CardContent>
<div class="flex flex-col gap-3">
<input
type="text"
placeholder="Wallet name (e.g. Main, Savings)"
class="flex h-8 w-full rounded-md border border-input bg-transparent px-2 py-1 font-mono text-xs"
bind:value={inputWalletName} />
<Textarea
placeholder="Enter your 12 or 24 word seed phrase"
bind:value={inputSeed} />
<input
type="password"
placeholder="Set a password (optional, used when Touch ID is unavailable)"
placeholder="Set a password (optional)"
class="flex h-8 w-full rounded-md border border-input bg-transparent px-2 py-1 font-mono text-xs"
bind:value={inputPassword} />
<Button
onclick={() =>
w.saveVault(inputSeed, inputPassword || undefined)}
disabled={w.loading || !inputSeed.trim()}>
{w.loading ? 'Saving...' : 'Save to Keychain'}
</Button>
<div class="flex gap-2">
<Button
onclick={() =>
w.createWallet(inputWalletName, inputSeed, inputPassword || undefined)}
disabled={w.loading || !inputSeed.trim() || !inputWalletName.trim()}>
{w.loading ? 'Saving...' : 'Save Wallet'}
</Button>
{#if showCreateForm}
<Button variant="outline" onclick={() => (showCreateForm = false)}>
Cancel
</Button>
{/if}
</div>
</div>
{#if w.error}
<p class="mt-3 text-red-500">{w.error}</p>
{/if}
</CardContent>
</Card>
{:else if !w.currentWalletId}
<Card>
<CardHeader>
<CardTitle>Wallets</CardTitle>
<CardDescription>Select a wallet to use</CardDescription>
</CardHeader>
<CardContent>
<div class="flex flex-col gap-2">
{#each w.wallets as wal}
<button
onclick={async () => {
if (wal.hasPassword) {
await w.selectWallet(wal.id)
} else {
await w.selectAndUnlockWallet(wal.id)
}
}}
class="flex w-full cursor-pointer items-center gap-3 rounded-md border border-input p-3 text-left hover:bg-muted transition-colors">
<WalletIcon size={20} class="shrink-0 text-muted-foreground" />
<div class="flex-1 min-w-0">
<p class="font-medium text-sm">{wal.name}</p>
<p class="text-xs text-muted-foreground">
{new Date(wal.createdAt).toLocaleDateString()}
</p>
</div>
<div class="flex items-center gap-1">
{#if wal.hasPassword}
<LockKeyhole size={14} class="text-muted-foreground" />
{/if}
</div>
</button>
{/each}
<Button variant="outline" onclick={() => (showCreateForm = true)} class="mt-2">
<Plus size={16} />
Add Wallet
</Button>
</div>
</CardContent>
</Card>
{:else if w.isLocked}
<Card>
<CardHeader>
<CardTitle>Wallet Locked</CardTitle>
<CardTitle>{w.currentWallet?.name ?? 'Wallet'} Locked</CardTitle>
<CardDescription>
Your seed is stored in the system keychain
Unlock to access your wallet
</CardDescription>
</CardHeader>
<CardContent>
@@ -140,7 +203,7 @@
{w.loading ? 'Unlocking...' : 'Unlock with Touch ID'}
</Button>
{/if}
{#if w.passwordSet}
{#if w.currentPasswordHash}
<div class="flex gap-2 items-end">
<input
type="password"
@@ -161,6 +224,9 @@
</Button>
</div>
{/if}
<Button variant="outline" onclick={() => w.clearSelection()}>
Pick another wallet
</Button>
</div>
{#if w.error}
<p class="mt-3 text-red-500">{w.error}</p>
@@ -186,7 +252,9 @@
<CardHeader>
<div class="flex items-center justify-between">
<div>
<CardTitle>Wallet</CardTitle>
<CardTitle>
{w.currentWallet?.name ?? 'Wallet'}
</CardTitle>
<CardDescription>Your wallet is unlocked</CardDescription>
</div>
</div>
@@ -268,7 +336,7 @@
<p class="mb-3 text-red-500">{w.error}</p>
{/if}
<div class="flex gap-2">
<div class="flex gap-2 flex-wrap">
<Button onclick={() => w.refresh()} disabled={w.loading}>
{#if w.loading}
<Loader />
@@ -280,6 +348,12 @@
onclick={() => navigate('/settings')}>
<SettingsIcon size={16} />
</Button>
<Button
variant="outline"
onclick={() => w.lock()}>
<LockKeyhole size={16} />
Lock
</Button>
<Button
variant="outline"
onclick={async () => {
+24
View File
@@ -89,6 +89,14 @@ export type TokenBalanceResult = {
logo?: string
}
export type EvmWalletInfo = {
id: string
name: string
hasPassword: boolean
vaultKey: string
createdAt: string
}
type RPC = {
bun: {
requests: {
@@ -212,6 +220,22 @@ type RPC = {
params: {}
response: string[]
}
evmCreateWallet: {
params: { name: string; phrase: string; passwordHash?: string }
response: { id: string; name: string; createdAt: string }
}
evmListWallets: {
params: {}
response: EvmWalletInfo[]
}
evmGetSeed: {
params: { vaultKey: string }
response: string
}
evmDeleteWallet: {
params: { id: string }
response: void
}
}
messages: {}
}
+130 -59
View File
@@ -1,6 +1,6 @@
import { mnemonicToAccount } from 'viem/accounts'
import { createPublicClient, http, formatEther } from 'viem'
import { electrobun, type TxEntry } from '$lib/electrobun'
import { electrobun, type TxEntry, type EvmWalletInfo } from '$lib/electrobun'
import { tryCatch } from '@koins/utils'
import { moneroWallet } from './monero-wallet.svelte.js'
@@ -51,12 +51,13 @@ export const EvmWallet = () => {
let balance = $state('0')
let tokenBalances = $state<TokenBalance[]>([])
let network = $state<NetworkId>('eth')
let vaultExists = $state(false)
let apiKey = $state('')
let transactions = $state<TxEntry[]>([])
let passwordHash = $state('')
let loading = $state(false)
let error = $state('')
let wallets = $state<EvmWalletInfo[]>([])
let currentWalletId = $state<string | null>(null)
let currentPasswordHash = $state<string | null>(null)
const net = () => networks.find((n) => n.id === network)!
@@ -79,21 +80,22 @@ export const EvmWallet = () => {
const init = async () => {
if (!electrobun.rpc) return
const [raw] = await tryCatch(
electrobun.rpc.request.getSecret({ service: 'koins', name: 'vault' }),
const [walletList] = await tryCatch(
electrobun.rpc.request.evmListWallets({}),
)
vaultExists = raw !== null && raw !== undefined
if (walletList) {
wallets = walletList
if (walletList.length === 1 && !currentWalletId) {
currentWalletId = walletList[0].id
}
}
const [key] = await tryCatch(
electrobun.rpc.request.getSecret({ service: 'koins', name: 'alchemy_key' }),
)
if (key) apiKey = key
const [ph] = await tryCatch(
electrobun.rpc.request.getSecret({ service: 'koins', name: 'vault_password' }),
)
if (ph) passwordHash = ph
await moneroWallet.checkStatus()
if (moneroWallet.installed && !moneroWallet.running && !moneroWallet.downloading) {
await moneroWallet.start()
@@ -119,21 +121,29 @@ export const EvmWallet = () => {
const logout = async () => {
await moneroWallet.stop()
accountType = null
clearWallet()
}
const clearWallet = () => {
seed = ''
address = ''
balance = '0'
tokenBalances = []
transactions = []
error = ''
currentPasswordHash = null
}
const loadSeed = async () => {
const unlockWallet = async (walletId: string) => {
if (!electrobun.rpc) return false
const [raw] = await tryCatch(
electrobun.rpc.request.getSecret({ service: 'koins', name: 'vault' }),
const wallet = wallets.find((w) => w.id === walletId)
if (!wallet) return false
currentWalletId = walletId
const [vaultSeed] = await tryCatch(
electrobun.rpc.request.evmGetSeed({ vaultKey: wallet.vaultKey }),
)
if (!raw) return false
seed = raw
if (!vaultSeed) return false
seed = vaultSeed
await refresh()
return true
}
@@ -144,48 +154,102 @@ export const EvmWallet = () => {
electrobun.rpc.request.biometricAuth({ reason: 'Unlock wallet' }),
)
if (!authed) return false
return loadSeed()
if (!currentWalletId) return false
await loadSeedForWallet(currentWalletId)
return !!seed
}
const unlockWithPassword = async (password: string) => {
if (!passwordHash) return false
if (!currentPasswordHash || !currentWalletId) return false
try {
const { salt, hash } = JSON.parse(passwordHash)
const { salt, hash } = JSON.parse(currentPasswordHash)
const { hash: check } = await hashPassword(password, salt)
if (check !== hash) return false
return await loadSeed()
return loadSeedForWallet(currentWalletId)
} catch {
return false
}
}
const setPassword = async (password: string) => {
if (!electrobun.rpc) return
const ph = await hashPassword(password)
const raw = JSON.stringify(ph)
await electrobun.rpc.request.setSecret({
service: 'koins', name: 'vault_password', value: raw,
})
passwordHash = raw
const loadSeedForWallet = async (walletId: string) => {
if (!electrobun.rpc) return false
const wallet = wallets.find((w) => w.id === walletId)
if (!wallet) return false
const [vaultSeed] = await tryCatch(
electrobun.rpc.request.evmGetSeed({ vaultKey: wallet.vaultKey }),
)
if (!vaultSeed) return false
seed = vaultSeed
await refresh()
return true
}
const saveVault = async (phrase: string, password?: string) => {
const selectWallet = async (walletId: string) => {
currentWalletId = walletId
clearWallet()
const wallet = wallets.find((w) => w.id === walletId)
if (!wallet) return
if (wallet.hasPassword && electrobun.rpc) {
const [ph] = await tryCatch(
electrobun.rpc.request.getSecret({
service: 'koins',
name: `evm_auth_${walletId}`,
}),
)
if (ph) {
currentPasswordHash = ph
}
} else {
currentPasswordHash = null
}
}
const selectAndUnlockWallet = async (walletId: string) => {
await selectWallet(walletId)
if (!currentPasswordHash && biometricAvailable) {
return unlockWithBiometrics()
}
return false
}
const createWallet = async (name: string, phrase: string, password?: string) => {
loading = true
error = ''
try {
mnemonicToAccount(phrase.trim())
await electrobun.rpc?.request.setSecret({
service: 'koins', name: 'vault', value: phrase.trim(),
})
let passwordHash: string | undefined
if (password) {
const ph = await hashPassword(password)
await electrobun.rpc?.request.setSecret({
service: 'koins', name: 'vault_password', value: JSON.stringify(ph),
})
passwordHash = JSON.stringify(ph)
}
const [result, resultError] = await tryCatch(
electrobun.rpc!.request.evmCreateWallet({
name,
phrase: phrase.trim(),
passwordHash,
}),
)
if (resultError) throw resultError
if (passwordHash) {
await electrobun.rpc?.request.setSecret({
service: 'koins',
name: `evm_auth_${result.id}`,
value: passwordHash,
})
}
const newWallet: EvmWalletInfo = {
id: result.id,
name,
hasPassword: !!passwordHash,
vaultKey: `evm_seed_${result.id}`,
createdAt: result.createdAt,
}
wallets = [...wallets, newWallet]
currentWalletId = result.id
if (passwordHash) currentPasswordHash = passwordHash
seed = phrase.trim()
vaultExists = true
await refresh()
} catch (e) {
error = e instanceof Error ? e.message : 'Invalid seed phrase'
@@ -194,6 +258,20 @@ export const EvmWallet = () => {
}
}
const deleteWallet = async (walletId: string) => {
await electrobun.rpc?.request.evmDeleteWallet({ id: walletId })
wallets = wallets.filter((w) => w.id !== walletId)
if (currentWalletId === walletId) {
clearWallet()
currentWalletId = wallets.length > 0 ? wallets[0].id : null
}
}
const clearSelection = () => {
clearWallet()
currentWalletId = null
}
const switchNetwork = async (id: NetworkId) => {
network = id
if (seed) await refresh()
@@ -246,24 +324,14 @@ export const EvmWallet = () => {
}
const lock = () => {
seed = ''
address = ''
balance = '0'
error = ''
tokenBalances = []
transactions = []
clearWallet()
}
const reset = () => {
seed = ''
address = ''
balance = '0'
error = ''
tokenBalances = []
transactions = []
clearWallet()
apiKey = ''
vaultExists = false
passwordHash = ''
wallets = []
currentWalletId = null
}
const resetApp = async () => {
@@ -287,34 +355,37 @@ export const EvmWallet = () => {
get networkName() { return net().name },
get symbol() { return net().symbol },
get explorerUrl() { return net().explorerUrl },
get vaultExists() { return vaultExists },
get networks() { return networks },
get apiKey() { return apiKey },
get transactions() { return transactions },
get passwordSet() { return !!passwordHash },
get loading() { return loading },
get error() { return error },
get isLocked() { return vaultExists && !seed },
set passwordHash(v: string) { passwordHash = v },
set vaultExists(v: boolean) { vaultExists = v },
get wallets() { return wallets },
get currentWalletId() { return currentWalletId },
get currentWallet() { return wallets.find((w) => w.id === currentWalletId) ?? null },
get isLocked() { return !!currentWalletId && !seed },
get hasWallets() { return wallets.length > 0 },
get currentPasswordHash() { return currentPasswordHash },
set apiKey(v: string) { apiKey = v },
set seed(v: string) { seed = v },
set error(v: string) { error = v },
init,
login,
logout,
refresh,
saveVault,
createWallet,
switchNetwork,
saveApiKey,
fetchTxHistory,
loadSeed,
lock,
reset,
resetApp,
unlockWithBiometrics,
unlockWithPassword,
setPassword,
selectWallet,
selectAndUnlockWallet,
unlockWallet,
deleteWallet,
clearSelection,
}
}