62 lines
2.1 KiB
TypeScript
62 lines
2.1 KiB
TypeScript
import { writable, derived } from 'svelte/store';
|
|
import type { Writable, Readable } from 'svelte/store';
|
|
import { WalletP2PKH, WalletHD } from '../wallet/index.js'; // Adjust import path as needed
|
|
import type { AddressListUnspent, Blockchain } from '../wallet/index.js'; // Adjust import path as needed
|
|
import type { Transaction } from '../primitives/index.js';
|
|
import type { HdPrivateNodeValid } from '@bitauth/libauth';
|
|
|
|
export class WalletP2PKHSvelte extends WalletP2PKH {
|
|
// Svelte stores
|
|
public unspents: Writable<AddressListUnspent['response']> = writable([]);
|
|
public transactions: Writable<Array<Transaction>> = writable([]);
|
|
|
|
// Derived store for balance
|
|
public balance: Readable<number> = derived(this.unspents, ($unspents) =>
|
|
$unspents.reduce((total, unspent) => total + unspent.value, 0),
|
|
);
|
|
|
|
constructor(privateKeyBytes: Uint8Array, electrum: Blockchain) {
|
|
super(privateKeyBytes, electrum);
|
|
this.events.on('unspentsUpdated', (unspents) => {
|
|
this.unspents.set(unspents);
|
|
});
|
|
this.events.on('transactionsUpdated', (transactions) => {
|
|
this.transactions.set(transactions);
|
|
});
|
|
}
|
|
}
|
|
|
|
export function useWalletP2PKHSvelte(
|
|
privateKeyBytes: Uint8Array,
|
|
electrum: Blockchain,
|
|
): WalletP2PKHSvelte {
|
|
return new WalletP2PKHSvelte(privateKeyBytes, electrum);
|
|
}
|
|
|
|
export class WalletHDSvelte extends WalletHD<WalletP2PKHSvelte> {
|
|
// Svelte stores
|
|
public shouldMonitor: Writable<boolean> = writable(false);
|
|
public wallets: Writable<Array<WalletP2PKHSvelte>> = writable([]);
|
|
|
|
// Derived store for total balance
|
|
public balance: Readable<number> = derived(this.wallets, ($wallets) =>
|
|
$wallets.reduce((total, wallet) => {
|
|
let walletBalance = 0;
|
|
wallet.balance.subscribe((value) => (walletBalance = value))();
|
|
return total + walletBalance;
|
|
}, 0),
|
|
);
|
|
|
|
constructor(
|
|
node: HdPrivateNodeValid,
|
|
electrum: Blockchain,
|
|
walletFactory = useWalletP2PKHSvelte,
|
|
) {
|
|
super(node, electrum, walletFactory);
|
|
this.events.on('walletsUpdated', (wallets) => this.wallets.set(wallets));
|
|
this.events.on('shouldMonitorUpdated', (shouldMonitor) =>
|
|
this.shouldMonitor.set(shouldMonitor),
|
|
);
|
|
}
|
|
}
|