'use client'; // Ethereum side: chains, wallet discovery (EIP-6963), deployment, // EIP-712 proposals and execution of SanarioMultisig. import { createPublicClient, createWalletClient, custom, http, getAddress, isAddress, encodeFunctionData, parseUnits, hashDomain, hashStruct, hashTypedData, recoverTypedDataAddress, erc20Abi, formatUnits, type Address, type Hex, } from 'viem'; import { mainnet, sepolia, base, arbitrum, optimism, polygon, bsc, holesky } from 'viem/chains'; import artifact from './artifact.json'; import { describeOp, type SignerOp } from './signers.ts'; export const ABI = artifact.abi as any; export const BYTECODE = artifact.bytecode as Hex; export const CHAINS = [mainnet, base, arbitrum, optimism, polygon, bsc, sepolia, holesky]; export const chainById = (id: number) => CHAINS.find((c) => c.id === id); export const explorer = (chainId: number) => chainById(chainId)?.blockExplorers?.default.url ?? ''; export type SignerKind = 'injected' | 'ledger' | 'trezor' | 'other'; export interface EthOwner { name: string; address: Address; kind?: SignerKind; path?: string } export interface EthVault { kind: 'eth'; id: string; name: string; chainId: number; address: Address; owners: EthOwner[]; threshold: number; createdAt: number; deployTx?: Hex; /** names for addresses proposed as owners but not yet on-chain */ labels?: Record; } export const TYPES = { Transaction: [ { name: 'to', type: 'address' }, { name: 'value', type: 'uint256' }, { name: 'data', type: 'bytes' }, { name: 'nonce', type: 'uint256' }, ], } as const; export interface Proposal { v: 1; chainId: number; wallet: Address; to: Address; value: string; // wei, decimal string data: Hex; nonce: string; title: string; /** owner address (checksummed) => signature hex, or "onchain" for approveHash */ signatures: Record; } export const domainOf = (p: { chainId: number; wallet: Address }) => ({ name: 'Sanario Multisig', version: '1', chainId: p.chainId, verifyingContract: p.wallet, }); export function typedData(p: Proposal) { return { domain: domainOf(p), types: TYPES, primaryType: 'Transaction' as const, message: { to: p.to, value: BigInt(p.value), data: p.data, nonce: BigInt(p.nonce) }, }; } /** JSON-safe EIP-712 payload (for Trezor / raw eth_signTypedData_v4). */ export function typedDataJson(p: Proposal) { return { domain: domainOf(p), types: { EIP712Domain: [ { name: 'name', type: 'string' }, { name: 'version', type: 'string' }, { name: 'chainId', type: 'uint256' }, { name: 'verifyingContract', type: 'address' }, ], ...TYPES, }, primaryType: 'Transaction', message: { to: p.to, value: p.value, data: p.data, nonce: p.nonce }, }; } export function hashes(p: Proposal) { const td = typedData(p); const domainHash = hashDomain({ domain: td.domain, types: { EIP712Domain: typedDataJson(p).types.EIP712Domain } as any }); const structHash = hashStruct({ data: td.message, primaryType: 'Transaction', types: TYPES as any }); return { domainHash, structHash, digest: hashTypedData(td as any) }; } export async function verifySignature(p: Proposal, sig: Hex): Promise
{ return getAddress(await recoverTypedDataAddress({ ...(typedData(p) as any), signature: sig })); } // --------------------------------------------------------- wallet discovery export interface InjectedWallet { uuid: string; name: string; icon: string; rdns: string; provider: any } /** EIP-6963: MetaMask, Rabby, Coinbase Wallet, Trust, OKX, Brave, Frame, Zerion, Phantom ... */ export function discoverWallets(onChange: (w: InjectedWallet[]) => void): () => void { const found = new Map(); const handler = (e: any) => { const { info, provider } = e.detail; found.set(info.uuid, { ...info, provider }); onChange([...found.values()]); }; window.addEventListener('eip6963:announceProvider', handler); window.dispatchEvent(new Event('eip6963:requestProvider')); // legacy fallback setTimeout(() => { const eth = (window as any).ethereum; if (!found.size && eth) { found.set('legacy', { uuid: 'legacy', name: eth.isMetaMask ? 'MetaMask' : 'Browser wallet', icon: '', rdns: 'legacy', provider: eth }); onChange([...found.values()]); } }, 400); return () => window.removeEventListener('eip6963:announceProvider', handler); } export async function connectInjected(w: InjectedWallet): Promise<{ account: Address; chainId: number }> { const accounts: string[] = await w.provider.request({ method: 'eth_requestAccounts' }); const chainId = parseInt(await w.provider.request({ method: 'eth_chainId' }), 16); return { account: getAddress(accounts[0]), chainId }; } export async function switchChain(w: InjectedWallet, chainId: number) { const chain = chainById(chainId)!; try { await w.provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x' + chainId.toString(16) }] }); } catch (e: any) { if (e?.code !== 4902) throw e; await w.provider.request({ method: 'wallet_addEthereumChain', params: [{ chainId: '0x' + chainId.toString(16), chainName: chain.name, nativeCurrency: chain.nativeCurrency, rpcUrls: chain.rpcUrls.default.http, blockExplorerUrls: [explorer(chainId)] }], }); } } export const publicClient = (chainId: number) => createPublicClient({ chain: chainById(chainId)!, transport: http() }); function walletClient(w: InjectedWallet, chainId: number, account: Address) { return createWalletClient({ chain: chainById(chainId)!, transport: custom(w.provider), account }); } // --------------------------------------------------------------- actions export async function deployVault(w: InjectedWallet, chainId: number, account: Address, owners: Address[], threshold: number) { const wc = walletClient(w, chainId, account); const hash = await wc.deployContract({ abi: ABI, bytecode: BYTECODE, args: [owners, BigInt(threshold)], account, chain: chainById(chainId)! }); const receipt = await publicClient(chainId).waitForTransactionReceipt({ hash }); if (!receipt.contractAddress || receipt.status !== 'success') throw new Error('Deployment failed.'); return { address: getAddress(receipt.contractAddress), tx: hash }; } export interface OnchainState { owners: Address[]; threshold: number; nonce: bigint; balance: bigint } export async function readState(chainId: number, wallet: Address): Promise { const pc = publicClient(chainId); const [owners, threshold, nonce, balance] = await Promise.all([ pc.readContract({ address: wallet, abi: ABI, functionName: 'getOwners' }) as Promise, pc.readContract({ address: wallet, abi: ABI, functionName: 'threshold' }) as Promise, pc.readContract({ address: wallet, abi: ABI, functionName: 'nonce' }) as Promise, pc.getBalance({ address: wallet }), ]); return { owners: owners.map((o) => getAddress(o)), threshold: Number(threshold), nonce, balance }; } export async function tokenInfo(chainId: number, token: Address, holder: Address) { const pc = publicClient(chainId); const [symbol, decimals, balance] = await Promise.all([ pc.readContract({ address: token, abi: erc20Abi, functionName: 'symbol' }), pc.readContract({ address: token, abi: erc20Abi, functionName: 'decimals' }), pc.readContract({ address: token, abi: erc20Abi, functionName: 'balanceOf', args: [holder] }), ]); return { symbol, decimals, balance, formatted: formatUnits(balance, decimals) }; } export async function signInjected(w: InjectedWallet, account: Address, p: Proposal): Promise { const wc = walletClient(w, p.chainId, account); return wc.signTypedData({ account, ...(typedData(p) as any) }); } export async function approveOnchain(w: InjectedWallet, account: Address, p: Proposal): Promise { const wc = walletClient(w, p.chainId, account); const { digest } = hashes(p); const hash = await wc.writeContract({ address: p.wallet, abi: ABI, functionName: 'approveHash', args: [digest], account, chain: chainById(p.chainId)! }); await publicClient(p.chainId).waitForTransactionReceipt({ hash }); return hash; } /** Anyone (owner or not) can submit once enough approvals exist; they only pay gas. */ export async function executeProposal(w: InjectedWallet, account: Address, p: Proposal, accountIsOwner = false): Promise { // an owner submitting the tx approves it implicitly (msg.sender), no signature needed const all = { ...p.signatures }; if (accountIsOwner && !all[account]) all[account] = 'onchain' as Hex; p = { ...p, signatures: all }; const signers = Object.keys(p.signatures).map((a) => getAddress(a)).sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1)); const sigs = signers.map((s) => (p.signatures[s] === ('onchain' as Hex) ? '0x' : p.signatures[s]) as Hex); const wc = walletClient(w, p.chainId, account); const pc = publicClient(p.chainId); const args = [p.to, BigInt(p.value), p.data, signers, sigs] as const; await pc.simulateContract({ address: p.wallet, abi: ABI, functionName: 'execute', args, account }); // surfaces revert reasons before paying gas const hash = await wc.writeContract({ address: p.wallet, abi: ABI, functionName: 'execute', args, account, chain: chainById(p.chainId)! }); const r = await pc.waitForTransactionReceipt({ hash }); if (r.status !== 'success') throw new Error('Execution reverted.'); return hash; } // ------------------------------------------------------- proposal builders export type ProposalKind = 'eth' | 'erc20' | 'addOwner' | 'removeOwner' | 'threshold' | 'custom'; export function buildCall(vault: EthVault, kind: ProposalKind, f: Record, tokenDecimals = 18): { to: Address; value: bigint; data: Hex; title: string } { const addr = (s: string, label: string) => { if (!isAddress(s?.trim() ?? '')) throw new Error(`${label} is not a valid address.`); return getAddress(s.trim()); }; switch (kind) { case 'eth': { const to = addr(f.to, 'Recipient'); const value = parseUnits(f.amount || '0', 18); if (value <= 0n) throw new Error('Enter an amount.'); return { to, value, data: '0x', title: f.title || `Send ${f.amount} ${chainById(vault.chainId)?.nativeCurrency.symbol}` }; } case 'erc20': { const token = addr(f.token, 'Token'); const to = addr(f.to, 'Recipient'); const amount = parseUnits(f.amount || '0', tokenDecimals); if (amount <= 0n) throw new Error('Enter an amount.'); return { to: token, value: 0n, data: encodeFunctionData({ abi: erc20Abi, functionName: 'transfer', args: [to, amount] }), title: f.title || `Send ${f.amount} ${f.symbol || 'tokens'}` }; } case 'addOwner': { const o = addr(f.owner, 'New owner'); return { to: vault.address, value: 0n, data: encodeFunctionData({ abi: ABI, functionName: 'addOwner', args: [o, BigInt(f.threshold)] }), title: `Add owner ${o.slice(0, 8)}… (threshold ${f.threshold})` }; } case 'removeOwner': { const o = addr(f.owner, 'Owner'); return { to: vault.address, value: 0n, data: encodeFunctionData({ abi: ABI, functionName: 'removeOwner', args: [o, BigInt(f.threshold)] }), title: `Remove owner ${o.slice(0, 8)}… (threshold ${f.threshold})` }; } case 'threshold': return { to: vault.address, value: 0n, data: encodeFunctionData({ abi: ABI, functionName: 'changeThreshold', args: [BigInt(f.threshold)] }), title: `Change threshold to ${f.threshold}` }; case 'custom': { const to = addr(f.to, 'Target'); const data = (f.data?.trim() || '0x') as Hex; if (!/^0x([0-9a-fA-F]{2})*$/.test(data)) throw new Error('Calldata must be 0x-prefixed hex.'); return { to, value: parseUnits(f.amount || '0', 18), data, title: f.title || 'Contract call' }; } } } /** One owner-management call (from planSignerChange) as a vault self-call. */ export function signerOpCall(vault: EthVault, op: SignerOp, name?: (a: string) => string): { to: Address; value: bigint; data: Hex; title: string } { const args = op.args.map((a) => (typeof a === 'number' ? BigInt(a) : getAddress(a))); return { to: vault.address, value: 0n, data: encodeFunctionData({ abi: ABI, functionName: op.fn, args }), title: describeOp(op, name) }; } // ------------------------------------------------- proposal sharing (no server) export function encodeProposal(p: Proposal): string { const json = JSON.stringify(p); return btoa(unescape(encodeURIComponent(json))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export function decodeProposal(s: string): Proposal { let t = s.trim(); const i = t.indexOf('#p='); if (i >= 0) t = t.slice(i + 3); let json: string; if (t.startsWith('{')) json = t; else json = decodeURIComponent(escape(atob(t.replace(/-/g, '+').replace(/_/g, '/')))); const p = JSON.parse(json); if (p.v !== 1 || !isAddress(p.wallet) || !isAddress(p.to)) throw new Error('Not a Sanario proposal.'); return { ...p, wallet: getAddress(p.wallet), to: getAddress(p.to) }; } /** Merge signatures from another copy of the same proposal (after verifying each). */ export async function mergeProposal(a: Proposal, b: Proposal, owners: Address[]): Promise { const same = a.chainId === b.chainId && a.wallet === b.wallet && a.to === b.to && a.value === b.value && a.data.toLowerCase() === b.data.toLowerCase() && a.nonce === b.nonce; if (!same) throw new Error('These are different transactions; signatures cannot be merged.'); const out = { ...a, signatures: { ...a.signatures } }; for (const [who, sig] of Object.entries(b.signatures)) { if (sig === ('onchain' as Hex)) { out.signatures[getAddress(who)] = sig; continue; } const rec = await verifySignature(a, sig); if (rec !== getAddress(who) || !owners.includes(rec)) throw new Error(`Invalid signature for ${who}.`); out.signatures[rec] = sig; } return out; }