-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet.js
More file actions
67 lines (57 loc) · 1.75 KB
/
wallet.js
File metadata and controls
67 lines (57 loc) · 1.75 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
import {
createPublicClient,
createWalletClient,
custom,
http,
formatEther,
} from 'https://esm.sh/viem@2';
import { baseSepolia, base } from 'https://esm.sh/viem@2/chains';
import { sdk } from 'https://esm.sh/@farcaster/miniapp-sdk';
// true = Base Sepolia (testnet), false = Base (mainnet)
const USE_TESTNET = false;
const CHAIN = USE_TESTNET ? baseSepolia : base;
let publicClient = null;
let walletClient = null;
let userAddress = null;
let walletConnected = false;
export async function initWallet() {
publicClient = createPublicClient({
chain: CHAIN,
transport: http(),
});
try {
const provider = sdk.wallet.ethProvider;
if (!provider) throw new Error('No Farcaster wallet provider');
walletClient = createWalletClient({
chain: CHAIN,
transport: custom(provider),
});
const addresses = await walletClient.requestAddresses();
if (addresses && addresses.length > 0) {
userAddress = addresses[0];
walletConnected = true;
}
} catch (e) {
console.warn('Wallet init:', e.message);
walletConnected = false;
}
return { address: userAddress, connected: walletConnected };
}
export function getPublicClient() { return publicClient; }
export function getWalletClient() { return walletClient; }
export function getAddress() { return userAddress; }
export function isConnected() { return walletConnected; }
export function getChain() { return CHAIN; }
export function shortAddr(addr) {
if (!addr) return '';
return addr.slice(0, 6) + '\u2026' + addr.slice(-4);
}
export async function getBalance() {
if (!publicClient || !userAddress) return '0';
try {
const bal = await publicClient.getBalance({ address: userAddress });
return formatEther(bal);
} catch {
return '0';
}
}