'use client'; import { useEffect, useState } from 'react'; import { formatEther, getAddress, isAddress, type Address, type Hex } from 'viem'; import { discoverWallets, connectInjected, switchChain, chainById, explorer, hashes, typedDataJson, verifySignature, signInjected, approveOnchain, executeProposal, encodeProposal, decodeProposal, mergeProposal, type InjectedWallet, type Proposal, } from '../lib/eth/wallet'; import { useAction, Btn, Err, Copy, SigBar, short } from './ui'; // ------------------------------------------------------------ connection export interface Conn { wallet: InjectedWallet; account: Address; chainId: number } export function useInjected() { const [wallets, setWallets] = useState([]); const [conn, setConn] = useState(null); useEffect(() => discoverWallets(setWallets), []); useEffect(() => { if (!conn) return; const p = conn.wallet.provider; const onAcc = (a: string[]) => (a.length ? setConn((c) => c && { ...c, account: getAddress(a[0]) }) : setConn(null)); const onChain = (id: string) => setConn((c) => c && { ...c, chainId: parseInt(id, 16) }); p.on?.('accountsChanged', onAcc); p.on?.('chainChanged', onChain); return () => { p.removeListener?.('accountsChanged', onAcc); p.removeListener?.('chainChanged', onChain); }; }, [conn?.wallet]); const connect = async (w: InjectedWallet) => { const r = await connectInjected(w); setConn({ wallet: w, ...r }); }; const ensureChain = async (chainId: number) => { if (!conn) throw new Error('Connect a wallet first.'); if (conn.chainId !== chainId) { await switchChain(conn.wallet, chainId); setConn({ ...conn, chainId }); } }; return { wallets, conn, connect, ensureChain, disconnect: () => setConn(null) }; } export function WalletBar({ inj }: { inj: ReturnType }) { const { busy, error, run } = useAction(); if (inj.conn) { return (
{inj.conn.wallet.icon && } {inj.conn.wallet.name} {short(inj.conn.account)} {chainById(inj.conn.chainId)?.name ?? `chain ${inj.conn.chainId}`}
); } return (
{inj.wallets.map((w) => ( run(w.uuid, () => inj.connect(w))}> {w.icon && } {w.name} ))} {!inj.wallets.length && No browser wallet found. Install MetaMask, Rabby, Coinbase Wallet or any EIP-6963 wallet. Ledger and Trezor can also sign directly below.}
); } // -------------------------------------------------- hardware signers export function HardwareSigner({ onSigned, proposal, owners }: { proposal: Proposal; owners: Address[]; onSigned: (who: Address, sig: Hex) => void }) { const [path, setPath] = useState("m/44'/60'/0'/0/0"); const { busy, error, run } = useAction(); const sign = (kind: 'ledger' | 'trezor') => run(kind, async () => { const { domainHash, structHash } = hashes(proposal); let addr: string, sig: Hex; if (kind === 'ledger') { const L = await import('../lib/hw/ledger'); addr = await L.ledgerEthAddress(path); if (!owners.includes(getAddress(addr))) throw new Error(`Ledger account ${addr} is not an owner of this vault. Check the derivation path.`); sig = (await L.ledgerEthSignTyped(path, domainHash, structHash)) as Hex; } else { const T = await import('../lib/hw/trezor'); addr = await T.trezorEthAddress(path); if (!owners.includes(getAddress(addr))) throw new Error(`Trezor account ${addr} is not an owner of this vault. Check the derivation path.`); sig = (await T.trezorEthSignTyped(path, typedDataJson(proposal), domainHash, structHash)) as Hex; } const rec = await verifySignature(proposal, sig); if (rec !== getAddress(addr)) throw new Error('Device returned a signature for a different account.'); onSigned(rec, sig); }); return (
setPath(e.target.value)} title="Derivation path (Ledger Live: m/44'/60'/N'/0/0)" /> sign('ledger')}>Sign with Ledger sign('trezor')}>Sign with Trezor
); } // ------------------------------------------------------- proposal card export function ProposalCard({ proposal, owners, threshold, nonce, inj, onChange, onExecuted, onDelete, executed, }: { proposal: Proposal; owners: Address[]; threshold: number; nonce: bigint | null; inj: ReturnType; onChange: (p: Proposal) => void; onExecuted: (tx: Hex) => void; onDelete?: () => void; executed?: string; }) { const { busy, error, run } = useAction(); const [paste, setPaste] = useState(''); const chain = chainById(proposal.chainId); const valid = Object.keys(proposal.signatures).filter((a) => owners.includes(getAddress(a))); const have = valid.length; const stale = nonce !== null && BigInt(proposal.nonce) < nonce; const blocked = nonce !== null && BigInt(proposal.nonce) > nonce; const { digest } = hashes(proposal); const link = typeof window !== 'undefined' ? `${window.location.origin}/app/eth/sign#p=${encodeProposal(proposal)}` : ''; const me = inj.conn?.account; const meIsOwner = !!me && owners.includes(me); const addSig = (who: Address, sig: Hex) => onChange({ ...proposal, signatures: { ...proposal.signatures, [who]: sig } }); return (

{proposal.title}

= threshold ? 'ok' : 'wait'}`}>{executed ? 'Executed' : stale ? 'Stale nonce' : have >= threshold ? 'Ready to execute' : `${have} of ${threshold} approvals`}
To{proposal.to}
Value{formatEther(BigInt(proposal.value))} {chain?.nativeCurrency.symbol}
Data{proposal.data === '0x' ? none (plain transfer) : proposal.data.length > 140 ? proposal.data.slice(0, 140) + '…' : proposal.data}
Nonce{proposal.nonce}{blocked && (waiting for nonce {String(nonce)} to execute first)}
EIP-712 hash{digest}

{owners.map((o) => {short(o, 4)}{proposal.signatures[o] === ('onchain' as Hex) ? ' (on-chain)' : ''})}

{executed ? (

Executed in {short(executed, 10)}

) : stale ? (

The vault has already executed a transaction with this nonce. This proposal can no longer run. Delete it.

) : ( <>

Approve

Before signing, check the destination and amount on your wallet or device screen.

run('inj', async () => { await inj.ensureChain(proposal.chainId); const sig = await signInjected(inj.conn!.wallet, inj.conn!.account, proposal); if ((await verifySignature(proposal, sig)) !== inj.conn!.account) throw new Error('Signature did not verify.'); addSig(inj.conn!.account, sig); })}>Sign with {inj.conn?.wallet.name ?? 'browser wallet'} run('onchain', async () => { await inj.ensureChain(proposal.chainId); await approveOnchain(inj.conn!.wallet, inj.conn!.account, proposal); addSig(inj.conn!.account, 'onchain' as Hex); })}>Approve on-chain (gas)

Collect approvals

Send this link to the other owners. It holds the transaction and the signatures collected so far, and nothing secret. Paste their returned link to merge signatures.