Web3 & DeFi Development
Patterns, tooling, and conventions for Web3 and decentralized finance (DeFi) applications across the Fro Bot-managed ecosystem.
Repositories
- marcusrbrown—tokentoilet — Token disposal and charity donation DeFi app (Next.js + Wagmi + Reown AppKit)
Wallet Integration Stack
The ecosystem currently standardizes on:
| Component | Tool | Notes |
|---|---|---|
| React hooks | Wagmi v3 (as of 2026-05-28 in marcusrbrown—tokentoilet) | Core wallet/chain interaction primitives; major bump from v2 landed via PR #837 lineage |
| Modal/UI | Reown AppKit (formerly WalletConnect Web3Modal) | Wallet connection modal and UI |
| Query layer | TanStack React Query | Async state for chain reads/writes |
| Supported wallets | MetaMask, WalletConnect, Coinbase Wallet | Per test suites in tokentoilet |
| Chains (v1.0 MVP) | Sepolia testnet only | SUPPORTED_CHAIN_IDS: [11155111]; mainnet chains (Ethereum, Polygon, Arbitrum) deferred |
Architectural Conventions
These patterns are enforced in marcusrbrown—tokentoilet via AGENTS.md and Fro Bot PR review prompts:
- Hook abstraction layer: Components never import wagmi or AppKit directly. A
useWallethook wraps all wallet state; domain hooks (useTokenApproval,useTokenBalance, etc.) wrap specific operations. 'use client'boundary: All Web3 components require the RSC client directive since wallet state is inherently client-side.- Error handling: Web3 operations use try/catch with
console.error. Connect/disconnect operations must never throw — failures are surfaced via state, not exceptions. - Functional state updates:
setX(prev => ...)pattern required in useEffect to prevent stale closure bugs common in async wallet flows. - Address handling: Checksummed addresses, validated before use.
- Token approvals: Infinite approvals flagged during review; amount validation required.
Security Patterns
- CSP: WalletConnect, Reown, Alchemy, Infura whitelisted in Content-Security-Policy connect-src
- No secrets in source: Private keys, mnemonics, RPC API keys must use environment variables, never hardcoded
- Reentrancy awareness: Contract interaction patterns reviewed for reentrancy concerns
- Dependency review:
actions/dependency-review-actionat moderate+ severity on PRs
Testing Patterns
Browser construction is not settlement (2026-10-07)
At 2c51ee39, marcusrbrown—tokentoilet documents a separate Playwright
suite driving its real wallet connection and approval/burn UI against a local
development server. A synthetic wallet and stubbed responses verify calldata and
UI states; the README explicitly excludes real broadcasts, funds, and on-chain
settlement. Browser coverage strengthens the UI-to-transaction construction seam
without establishing chain execution correctness.
Its E2E Tests CI job runs validate:e2e-boundary before Chromium, supplies dummy
public provider configuration, and enables environment validation even though
other CI jobs skip it. pnpm test remains Vitest-only; pnpm test:e2e is separate,
and the aggregate validate script includes neither E2E nor the Next.js build.
Presence of these commands and jobs does not prove they passed or are required
for merge.
Sources: E2E README, CI workflow, manifest.
Existing unit-test patterns
- Co-located test files (
*.test.ts(x)) alongside hook/component source - Mocked wallet providers (wagmi, AppKit) in test setup
- Wallet-specific test suites per connector (MetaMask, WalletConnect, Coinbase)
- Computed property names for hook mocks to avoid ESLint warnings
- Vitest as test runner with coverage via
@vitest/coverage-v8
Environment Configuration
- Typed env validation via
@t3-oss/env-nextjs+ Zod - Access via
import {env} from '@/env', neverprocess.env SKIP_ENV_VALIDATION=truein CI buildsNEXT_PUBLIC_SEPOLIA_RPC_URLfor testnet RPC endpoint (replaces hardcoded Alchemy demo key as of MVP)
MVP Architecture (2026-04-17)
The first functional disposal flow (PR #911 in marcusrbrown—tokentoilet) uses a burn-address mechanism on Sepolia:
- No smart contracts yet — tokens are sent to a dead address; custom contracts (
TokenToilet.sol,CharitySprinkler.sol,ProofOfDisposal.sol) are roadmap items - Multi-step UI:
DisposalFlowcomponent orchestrates token selection → network validation → approval → burn transfer NetworkGuardvalidates the connected wallet is on Sepolia before rendering disposal UI- Keyed
DisposalExecutor— each token gets a freshuseTokenDisposalhook instance via React key, preventing staleisSuccess/errorstate across multi-token disposals - Deployment: Vercel GitHub integration handles preview (PRs) and production (main push) — no CI deploy jobs
Token Discovery via Alchemy (2026-07-03)
The first non-scaffold discovery implementation landed in marcusrbrown—tokentoilet (PR #1179). Patterns worth carrying forward to other Web3 apps:
- Enumerate real holdings, not a static list.
useTokenDiscoverycalls Alchemy’salchemy_getTokenBalanceswith the connected wallet address to list actual ERC-20 balances. The wallet address is sent to Alchemy — this is the required data flow for discovery to function and is documented as such in.env.example. - Fail closed, never fall back to a hardcoded list. With no
NEXT_PUBLIC_ALCHEMY_API_KEY, the app renders a “discovery unavailable” state. A silent static-list fallback would mislead users about their actual holdings; the absence of a key is surfaced, not papered over. - Browser-exposed key → domain allowlist. The Alchemy key is a
NEXT_PUBLIC_*var, so it reaches the client. The abuse control is not secrecy but a domain allowlist configured in the Alchemy dashboard. - Rejected key ≠ transient error. A 401/rejected key is classified as unavailable (permanent), not retryable (#1183). This prevents a hot retry loop hammering the provider with a key that will never succeed.
- Skip, don’t abort. An unmapped chain skips that chain rather than aborting the whole scan (#1180) — partial discovery beats total failure.
- Surface structured errors. Discovery errors propagate to the UI as structured messages (#1184), not swallowed console noise. Provider error-shape captured as a
docs/solutionslearning (#1186).
Simulate Before Signing (2026-07-03)
marcusrbrown—tokentoilet PR #1175 added a transfer simulation step before prompting the user for a signature. Simulating the transaction catches reverts before they cost a signature or gas. This is now an enforced expectation in the Fro Bot Web3-security review rubric (“simulate before prompting signature”) — a pattern that should generalize to any signature-gated on-chain write.
Privacy: Telemetry Defaults Off (2026-07-03)
Analytics telemetry in marcusrbrown—tokentoilet defaults to opt-in / off (PR #1174). The default was deliberately set to off rather than shipping opt-out telemetry, consistent with the no-unconsented-telemetry baseline that governs the ecosystem. When adding any analytics to a Web3 app here, off-by-default is the required posture.
Mainnet Readiness: Explicit No-Go (2026-07-03)
A readiness spike (#1178) concluded marcusrbrown—tokentoilet stays Sepolia-only until token discovery is proven correct. The SUPPORTED_CHAIN_IDS: [11155111] lock is now a documented decision backed by a spike, not merely an unfinished feature. Stale multi-chain RPC env vars were removed (#1176) and invalid multi-chain integration tests deleted with E2E gaps tracked separately (#1172). Pattern: gate mainnet on read-path correctness (discovery) before write-path expansion.
Bundle Optimization: Code-Splitting the Web3 Tree (2026-07-18)
Wallet stacks are heavy — wagmi, AppKit, and their connector transitives are among the largest client dependencies a Web3 app carries. marcusrbrown—tokentoilet built a Dynamic Loading Infrastructure to keep that weight off the initial payload (CHANGELOG.md Unreleased, #641–#646). Patterns worth generalizing:
- Defer the Web3 tree behind
next/dynamic. 10+ dynamic component wrappers put wallet/token UI behind module-level dynamic imports with Suspense boundaries, so the connect-and-dispose chrome loads on demand rather than on first paint. - Shape the wait with skeletons, not spinners. 7 specialized skeleton loaders give the deferred components sized placeholders, avoiding layout shift when the chunk resolves.
- Retry chunk loads with backoff. A dedicated error boundary retries failed dynamic imports
1s→2s→4s→8s(capped) instead of hard-failing on a transient chunk-load error — the same exponential-backoff discipline applied to provider calls, now at the module-load layer. - Instrument import performance. Import timings are captured via telemetry. (Note: keep this within the no-unconsented-telemetry baseline — performance instrumentation is lower-stakes than analytics, but the consent posture still applies.)
- Virtualize long lists. Real token discovery can return long holdings lists;
@tanstack/react-virtualwas added to virtualize rendering so list length doesn’t inflate the DOM. - Staged win caveat. The infrastructure targets a 50–100 KB (10–18%) initial-bundle reduction but is marked “complete, awaiting feature-page implementation” — the machinery exists before the payoff lands. When adopting this pattern, budget for the integration step, not just the infrastructure.
Migration Notes: Wagmi v2 → v3 (2026-05-28)
The useWallet abstraction in marcusrbrown—tokentoilet paid off during the wagmi v2 → v3 upgrade — the firewall between components and the wagmi API meant the major version bump largely contained itself inside the hooks/ directory. The pattern’s value: every component that uses useWallet instead of useAccount/useConnect directly is one less site that needs touching when wagmi changes shape. Watch for this when migrating other Web3 apps in the portfolio.
Addendum (2026-09-07) — the abstraction contained the code and not the documentation. Three months after the v2 → v3 cutover, the repo’s .github/copilot-instructions.md and both prompts in fro-bot.yaml still describe the stack as “Wagmi v2”. The insulating property that made the migration cheap in source is exactly what let the prose stay wrong without anything breaking: nothing compiles the prompt. When a hook abstraction absorbs a major bump, deliberately grep the non-code surfaces — prompts, agent instructions, READMEs, CHANGELOGs — because the usual signal that a version reference is stale (a build failure) is the thing the abstraction removed. See github-actions-ci § Prompt Text Is a Dependency With No Dependency Bot (2026-09-07 addendum).
Security Posture as a Merge-Rate Problem (2026-09-07)
A Web3 app’s dependency surface is unusually deep — wallet connectors, RPC clients, and crypto primitives pull long transitive trees — so pnpm.overrides-style advisory remediation is routine maintenance rather than an exception. marcusrbrown—tokentoilet shows what happens when that routine has no merge path.
- The ledger is the right mechanism.
pnpm-workspace.yamlcarries ~28overridesentries pinning transitive floors (axios, undici, ws, form-data, js-yaml, brace-expansion, postcss, rollup, vite, yaml, and both deprecated@metamask/sdk*packages), one line per advisory, alongsideallowBuilds,minimumReleaseAgeExclude, andpeerDependencyRules. Single-source, diffable, greppable — the same shape used at marcusrbrown—marcusrbrown-github-io and marcusrbrown—marcusrbrown. - Six more lines are stranded in unmerged PRs.
fast-uri,sharp,js-yaml,brace-expansion,nanoid, and an axios floor-widening sit in six green, review-free, one-line PRs aged 29–48 days, whilepnpm auditreports 24 findings and Dependabot reports 19 open moderate-or-higher alerts. - The CI security gate cannot see it.
actions/dependency-review-actionruns onpull_requestonly. It compares a diff against advisories; it does not audit the default branch. A repo can accumulate 19 open alerts onmainwith a permanently greenSecurity Auditcheck.
Two rules for Web3 repos specifically, where the transitive surface guarantees a steady advisory stream:
- An override ledger needs a merge path proportional to its update rate. Advisory remediation arrives continuously; if only one identity’s PRs automerge, remediation authored by any other identity queues indefinitely. Decide which identity owns ledger edits and give that identity a drain.
- PR-scoped dependency review is a change gate, not a posture monitor. Pair it with a scheduled
pnpm audit(or equivalent) against the default branch that can actually go red, or the only thing reporting your posture will be an agent writing prose into an issue nobody gates on.
Detail on both, including the per-PR breakdown, lives on marcusrbrown—tokentoilet and in github-actions-ci § Merge Gates Sorted by Authorship, Not Quality (2026-09-07 addendum).
2026-10-07 qualification: At 2c51ee39, the PR-only Security Audit job now
combines dependency review with a blocking installed-production-tree audit and
an advisory full-tree audit. The September description of dependency-review-only
coverage is superseded; its broader warning about absent default-branch monitoring
still applies to this workflow. Current advisory counts and remediation queue
state were not surveyed. Both the root README and Fro Bot prompts also retain
Wagmi v2 prose against wagmi: ^3.0.0; the documented migration-context drift
remains directly observable.
2026-10-22 reconfirmation and audit-scope qualification: Public main remains
at 2c51ee39; re-reading the manifest, READMEs, and workflow files reconfirms the
October 7 testing and audit contracts. The security workflow’s comment describes
its production audit as covering advisories reachable from shipped code. More
precisely, pnpm audit --prod --audit-level moderate filters by production
dependency classification and severity; it does not perform application-level
reachability analysis. Conversely, the advisory full-tree audit is not evidence
that every devDependency is harmless: build tooling can affect shipped artifacts.
Keep dependency class, runtime reachability, and supply-chain exposure distinct.
Neither command was run against the target during this bounded survey, so no
current advisory count or clean-security claim follows.
Source: security-audit job.