Blockchain Integration Guide
What is a blockchain?
Reads are free RPC calls; writes are key-signed txs that cost gas and finalise over confirmations.
EOAs (key-controlled) and contract accounts share one state machine, the EVM. A write is signed locally (key never leaves the wallet), broadcast to the mempool, included by a validator, then settles over N confirmations. Use viem (createPublicClient for reads; simulateContract → writeContract → waitForTransactionReceipt for writes) or ethers v6. Work in bigint wei; parseUnits/formatUnits only at the edge. For codeAmani (US-first), accepting USDC goes through Stripe's stablecoin payment method (settles to USD, no wallet code). Build on-chain with viem only when the product needs it, and for Kenya-targeted projects keep M-Pesa as the last mile.
Six things to get right
The concepts that separate "I shipped a payment rail" from "I lost the keys." Tap a card for the details.
The trilemma — pick two, see what you give up
Every chain optimises at most two of decentralisation, security, and scalability. Choose your two and watch which real-world archetype — and which throughput/fee/finality reality — that commits you to. This single trade-off explains why rollups like Base exist — and why the L1-vs-L2 choice got closer after Fusaka.
Base-layer L1 (Ethereum / Bitcoin)
e.g. Ethereum mainnet, Bitcoin
Maximally trustless and secure — the right home for high-value settlement and the security other layers borrow. Since Fusaka raised the gas limit to 60M, fees are usually low; you still pay in throughput and fee volatility under load.
The escape hatch: L2 rollups (Base, Arbitrum, Optimism) execute cheaply off-chain and post proofs back to Ethereum L1 — so they feel scalable while inheriting L1 security. With L1 now cheap too, pick mainnet vs an L2 by liquidity and volume. And for simply accepting USDC, codeAmani's default is Stripe — no chain code at all.
██████╗ ██╗ ██████╗ ██████╗██╗ ██╗ ██████╗██╗ ██╗ █████╗ ██╗███╗ ██╗
██╔══██╗██║ ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██║ ██║██╔══██╗██║████╗ ██║
██████╔╝██║ ██║ ██║██║ █████╔╝ ██║ ███████║███████║██║██╔██╗ ██║
██╔══██╗██║ ██║ ██║██║ ██╔═██╗ ██║ ██╔══██║██╔══██║██║██║╚██╗██║
██████╔╝███████╗╚██████╔╝╚██████╗██║ ██╗╚██████╗██║ ██║██║ ██║██║██║ ╚████║
╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝Blockchain Integration Guide
Focus: what a blockchain actually is (a replicated append-only ledger nobody owns), the trade-off behind every design choice (the trilemma), what changed on Ethereum in 2025–2026, and where it earns its keep for codeAmani. That means stablecoin acceptance through Stripe by default, direct on-chain settlement only when a product needs it, and M-Pesa as the last mile for Kenya-targeted projects. The guide is EVM-anchored, mostly about reads, and keeps secrets server-side, with a short Solana section.
Overview
A blockchain is a shared, append-only ledger copied across thousands of independent computers. A new entry (a "block") is only accepted if most of them agree it follows the rules. Each block carries the cryptographic hash of the one before it, so the chain is tamper-evident: change one old transaction and every later block's hash breaks, and the network rejects your fork. No single party (no bank, no company, no government) can quietly edit it. That one property, verifiable state without a trusted operator, is the whole point. Everything else is engineering trade-offs around it.
Three honest truths frame every blockchain decision:
- You can't have it all: the trilemma. A chain optimises at most two of decentralisation, security and scalability. Ethereum L1 picks decentralisation + security. L2 rollups (Base, Arbitrum, OP Mainnet) run transactions cheaply off-chain and inherit Ethereum's security by posting data and proofs back to L1. Since 2025 the gap has narrowed: L1 fees are now often cents (see Network state below), so "mainnet is too expensive" is no longer an automatic filter.
- Reads are free and easy; writes are slow, public and cost gas. Querying chain state (a balance, a token's supply) is a cheap RPC call. Writing (a transfer, a contract call) is signed by a private key, broadcast, included in a block by a validator, and costs a gas fee. Until it has enough confirmations it can still be reorged, so writes become final over time, not instantly.
- Code is law, and bugs are permanent. A deployed smart contract can't be changed and usually controls real money. There is no "undo" and no support line. That's why audits, well-tested token standards (ERC-20, ERC-721) and "don't roll your own crypto" matter more here than almost anywhere else.
For codeAmani, the realistic, non-speculative use is digital dollars. US customers who want to pay in USDC can do it through Stripe with no wallet code on our side. Building directly on chain (viem + USDC on Base or mainnet) is for products whose core feature is on-chain: payouts to wallets, verifiable records, wallet sign-in, or cross-border settlement behind an M-Pesa cash-out for Kenya-targeted projects.
Official Documentation
| Source | URL | What it covers |
|---|---|---|
| Ethereum dev docs | https://ethereum.org/developers/docs/ | Accounts, transactions, gas, EVM, consensus, networks |
| Building on Ethereum in 2026 (EF) | https://ethereum.org/latest/building-on-ethereum-in-2026/ | What Dencun / Pectra / Fusaka changed for builders |
| viem | https://viem.sh/docs/getting-started | Modern TypeScript Ethereum interface (clients, reads, writes, ABIs) |
| wagmi | https://wagmi.sh/react/getting-started | React hooks for EVM wallets (v3) |
| ethers v6 | https://docs.ethers.org/v6/ | Mature JS library: providers, contracts, wallets, formatting |
| Solana Kit | https://www.solanakit.com/docs | Current Solana JS SDK (@solana/kit) |
| Solidity | https://docs.soliditylang.org/ | The main smart-contract language |
| Circle (USDC) | https://developers.circle.com/stablecoins | USDC contract addresses, supported chains, APIs |
| Stripe stablecoin payments | https://docs.stripe.com/payments/stablecoin-payments | Accept USDC/USDP/USDG through Checkout, Elements, Billing |
| Base upgrades | https://docs.base.org/upgrades/overview | Base network upgrade history and schedule |
Network state (verified 2026-10-20)
The mental model many people formed in 2021–2023 is out of date. What builders need to know now:
| Change | When | What it means for you |
|---|---|---|
| Pectra: EIP-7702 + more blobs | Mainnet May 7, 2025 | A plain wallet (EOA) can point at smart-account code: batching, gas sponsorship, session keys, passkeys, same address. Ask the wallet for batches through ERC-5792 wallet_sendCalls (viem sendCalls) rather than building 7702 setup yourself. |
| Fusaka: PeerDAS, 60M gas limit | Mainnet Dec 3, 2025 | Cheaper L2 data; L1 gas limit standardised at 60M; a per-transaction cap of ~16.78M gas (EIP-7825) that very large deploys or multicalls must fit inside; native P-256 (passkey) signature verification (EIP-7951). |
| L1 fees | 2026 | The EF reports standard gas around 0.15–0.5 gwei in spring 2026; an ERC-20 transfer was about $0.08 at their example prices. Use gas maths, not folklore. |
| Glamsterdam: ePBS + block-level access lists | ethereum.org: "Expected on mainnet Q4 2026 · Date not yet confirmed" | Aims to raise the gas limit toward ~200M. Little app-level surface change. Watch for the fork date before deploying anything gas-sensitive. |
| Holesky testnet | Deprecated Sept 2025 | App developers use Sepolia; validator/staking testing uses Hoodi. |
| Base Cobalt upgrade | Base mainnet Sept 30, 2026 | Base's third upgrade of 2026 (conditional/"validity" transactions, B20 token-standard changes). Third-party coverage calls it largely backward-compatible for deployed apps. |
How a block chain holds together
Each block bundles a batch of transactions plus the hash of the previous block. Because the hash is computed from the contents, any change anywhere ripples forward and breaks every later block. That's what makes the ledger tamper-evident rather than just "a database with backups."
Consensus is how the network agrees on the next block. Ethereum uses Proof of Stake: validators lock up (stake) ETH and are chosen to propose and attest blocks, and misbehaviour gets their stake slashed. This replaced energy-hungry Proof of Work.
The transaction lifecycle (a write)
Reading is a free RPC query. Writing money or state is the part with real consequences: sign locally, broadcast, wait for inclusion, then wait for finality.
Key terms:
| Term | Meaning |
|---|---|
| Account / address | 0x… 20-byte identifier. EOA = controlled by a private key; contract account = controlled by code. Since EIP-7702 an EOA can also delegate to contract code. |
| Private key / seed phrase | The secret that authorises spends. Whoever holds it owns the funds. Never on a server, never in git, never NEXT_PUBLIC_*. |
| Gas | Compute units a tx uses × gas price (in gwei). That's the fee. Failed txs still cost gas. |
| Nonce | Per-account counter. It orders an account's txs and prevents replays. |
| Confirmation / finality | Blocks built on top of yours. More confirmations = harder to reverse. Treat money as received only past your finality threshold. |
| Wei / gwei / ether | Denominations. 1 ether = 10⁹ gwei = 10¹⁸ wei. Always work in the smallest unit (bigint) and format only for display. |
Taking stablecoin payments: decision order
- Default (US-first): Stripe. Turn on the stablecoin payment method in the Stripe Dashboard and it appears in Checkout, Elements, Payment Links, Invoicing and Billing (subscriptions included). As of 2026-10-20 the docs say: accepted tokens are USDC (Tempo, Ethereum, Solana, Polygon and Base networks), USDP (Ethereum and Solana, US-only) and USDG (Ethereum, US-only); presentment currency is USD; payments settle in your Stripe balance in your local currency; there's a 10,000 USD per-transaction limit for customers; there are no disputes/chargebacks; refunds go back as stablecoins to the customer's original wallet; manual capture isn't supported. US businesses are supported, and EU/HK/MX/CH are in private preview. You write no wallet code and hold no keys. See the
stripe/guide. - Kenya-targeted projects: M-Pesa. M-Pesa via Daraja stays the payment rail. A stablecoin can sit behind it as a cross-border settlement layer, but only through a licensed on/off-ramp partner (see below).
- Direct on-chain only when the product itself needs it. That's the rest of this guide.
Reading the chain (viem)
viem (v2, 2.57.x) is the modern, type-safe TypeScript interface. A Public Client reads. v3 exists only as a next preview, so stay on v2.
npm i viem// lib/chain.ts — server-side only
import { createPublicClient, http } from "viem";
import { base } from "viem/chains"; // Base L2 — swap for `mainnet` if L1 fits better
export const publicClient = createPublicClient({
chain: base,
transport: http(process.env.RPC_URL), // provider URL with key; falls back to a public node if omitted
});
const block = await publicClient.getBlockNumber();
const wei = await publicClient.getBalance({ address: "0x0000000000000000000000000000000000000000" });Reading an ERC-20 (e.g. a USDC balance)
Tokens like USDC are smart contracts, not the chain's native balance. You read them by calling balanceOf on the contract.
import { erc20Abi, formatUnits } from "viem";
import { publicClient } from "./chain";
const USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base (Circle docs)
const [symbol, decimals, raw] = await Promise.all([
publicClient.readContract({ address: USDC, abi: erc20Abi, functionName: "symbol" }),
publicClient.readContract({ address: USDC, abi: erc20Abi, functionName: "decimals" }),
publicClient.readContract({
address: USDC,
abi: erc20Abi,
functionName: "balanceOf",
args: ["0x0000000000000000000000000000000000000000"],
}),
]);
const human = formatUnits(raw, decimals); // e.g. "42.5" — never do float math on raw bigint balancesThe same read in ethers v6
ethers (6.17.x) is the mature alternative that many existing dapps use.
import { JsonRpcProvider, Contract, formatUnits } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const abi = [
"function decimals() view returns (uint8)",
"function symbol() view returns (string)",
"function balanceOf(address) view returns (uint)",
];
const usdc = new Contract("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", abi, provider);
const decimals = await usdc.decimals();
const balance = await usdc.balanceOf("0x0000000000000000000000000000000000000000");
const human = formatUnits(balance, decimals);viem vs ethers for a new codeAmani project: prefer viem. It has a smaller bundle, first-class TypeScript inference, and it pairs with wagmi for React wallet hooks. Use ethers when you're working in an existing codebase that already uses it.
Writing the chain (and why the key stays off your server)
A write is signed by a private key. There are two safe places for that key, and your app server is never one of them:
- User-custodied (consumer apps): the user's wallet holds the key. Your frontend builds the tx and the wallet signs it. Use wagmi + viem with a connect UI:
- wagmi v3 (
3.7.x):useAccountis renameduseConnection(core:getConnection/watchConnection/switchConnection), and connector SDKs are no longer bundled, so install only the ones you use. - RainbowKit
2.2.11still declareswagmi ^2.9.0. If you use RainbowKit, pin wagmi2.19.5until RainbowKit ships v3 support. - Reown AppKit (
@reown/appkit1.8.x; its wagmi adapter acceptswagmi >=2.19.5) works with wagmi v3.
- wagmi v3 (
- App-custodied (treasury/automation): use a KMS/HSM-backed signer (AWS KMS, GCP KMS) or a custody provider, so the raw key never sits in app memory or env files. viem accepts custom accounts. One community AWS option is
viem-kms-signer(1.0.1); it isn't an official viem package, so review it before use.
// Frontend write with a browser wallet (viem) — assert the chain, simulate, then send.
import { createWalletClient, custom, parseUnits, erc20Abi, type EIP1193Provider } from "viem";
import { base } from "viem/chains";
import { publicClient } from "./chain";
declare const ethereum: EIP1193Provider; // injected by the user's wallet
const walletClient = createWalletClient({ chain: base, transport: custom(ethereum) });
const [account] = await walletClient.getAddresses();
// 0. Never write on the wrong network.
if ((await walletClient.getChainId()) !== base.id) await walletClient.switchChain({ id: base.id });
// 1. Simulate — catches reverts BEFORE the user pays gas.
const { request } = await publicClient.simulateContract({
account,
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
abi: erc20Abi,
functionName: "transfer",
args: ["0x0000000000000000000000000000000000000001", parseUnits("10", 6)], // 10 USDC (6 decimals)
});
// 2. The wallet signs & broadcasts; the key never leaves the wallet.
const hash = await walletClient.writeContract(request);
// 3. Wait for your finality threshold before treating it as paid.
const receipt = await publicClient.waitForTransactionReceipt({ hash, confirmations: 3 });The simulate → write → wait sequence is the standard safe pattern. Simulation surfaces a revert before any gas is spent, and waitForTransactionReceipt is where you enforce your finality threshold.
Batched writes (EIP-5792, post-Pectra)
For "approve + pay" style flows, ask the wallet for a batch with walletClient.sendCalls({ calls: [...] }) and wait with walletClient.waitForCallsStatus({ id }). The wallet decides whether to use EIP-7702, ERC-4337 or something else. Treat a delegation target (the code an EOA points at) as wallet infrastructure. Never ask users to delegate to app-controlled code. See PATTERNS.md.
Solana in one section
Solana is a high-throughput L1 (the "fewer, beefier validators" corner of the trilemma) with deep USDC liquidity, and Stripe accepts USDC on Solana. For new JS work use @solana/kit (8.5.x). @solana/web3.js jumped to 3.x on 2026-10-01 and now depends on @solana/kit; the 1.x class-based API (Connection, PublicKey) is legacy.
import { address, createSolanaRpc } from "@solana/kit";
const rpc = createSolanaRpc(process.env.SOLANA_RPC_URL ?? "https://api.devnet.solana.com");
const { value: lamports } = await rpc.getBalance(address("GdnSyH3YtwcxFvQrVVJMm1JhTS4QVX7MFsX56uJLUfiZ")).send();USDC mints (Circle): mainnet EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v, devnet 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU. A runnable token-balance read is in examples/solana-usdc-balance.ts.
Smart contracts in one breath
A smart contract is code (usually Solidity, solc 0.8.37) deployed to an address. It runs on the EVM exactly as written, on every validator, forever. Mostly you consume existing contracts through their ABI (the JSON describing their functions) rather than writing your own. When you do write one:
- Don't reinvent standards. Use audited OpenZeppelin implementations (
@openzeppelin/contracts5.6.x) of ERC-20, ERC-721/1155, access control and pausability. - Immutability cuts both ways. Plan upgrades (proxy patterns) before you deploy, or accept that the bytecode is final.
- Respect the Fusaka per-tx gas cap (~16.78M). Very large deploys must fit inside it.
- Test on a testnet first (Base Sepolia, Ethereum Sepolia; not Holesky, which is deprecated) with free faucet funds. Same discipline as Stripe test mode, or the Daraja sandbox for Kenya projects.
Possible use cases for codeAmani (mapped to the existing stack)
| Use case | What blockchain adds | Builds on (repo guide) |
|---|---|---|
| Accept USDC from US customers | No chargebacks; customers pay from their own wallet; you get USD. No on-chain code. | stripe |
| Stablecoin payouts to wallets | Pay suppliers, creators or gig workers in digital dollars, globally, in seconds. | stripe (payouts), supabase/neon (ledger) |
| Cross-border settlement → M-Pesa (Kenya-targeted) | USDC moves value across borders cheaply, then a licensed partner off-ramps to M-Pesa. | MPESA_PATTERNS.md, daraja api |
| On-chain proof / provenance | Anchor a document or event hash on-chain for tamper-evident verification, with no token speculation. | supabase (store the doc, index the tx) |
| Auditable payment ledger | Mirror on-chain transfers into Postgres; dedupe on transactionHash + logIndex, like webhook idempotency. | supabase/neon, webhooks |
| Wallet-based identity / access | Sign-In with Ethereum (a signed message, no gas) as passwordless login or token-gated access, alongside Clerk. | clerk |
| Transparent disbursements (NGO/treasury) | Publicly checkable fund flows for grants or community payouts. | supabase (off-chain metadata) |
US regulation status (checked 2026-10-20; not legal advice)
Where a project touches stablecoins, these are the facts to plan around. Have counsel confirm before launch.
- GENIUS Act (payment stablecoins) is law, enacted July 18, 2025. Only permitted payment stablecoin issuers may issue payment stablecoins in the US, and issuers may not pay holders interest or yield just for holding. The Act takes effect on the earlier of January 18, 2027, or 120 days after final regulations (OCC proposed rule, Federal Register 2026-03-02). From July 18, 2028, digital asset service providers generally may not offer or sell payment stablecoins to people in the US unless a licensed issuer issued them (Treasury press release sb0605).
- Rulemaking is still in progress. The OCC proposed its rule in Feb 2026 (Bulletin 2026-3), and FDIC, NCUA and Treasury proposals followed. The Federal Reserve's proposal was published 2026-09-29. As of today we found no final OCC rule. The Comptroller has publicly pointed to finalising "in the very near term" / by November (reported, not confirmed from an OCC primary source).
- The CLARITY Act (market structure) is not law. Senate cloture failed 49–50 on September 15, 2026 (law-firm analyses; the bill remains on the Senate calendar). State money-transmitter and virtual-currency licensing still apply.
- What this means for codeAmani: we never issue a stablecoin, never pay yield on stablecoin balances, and never custody customer crypto ourselves. Accept through Stripe, or move funds through licensed partners (issuer/on-ramp/off-ramp/custody). Keep KYC/AML with the licensed partner. Re-check this section when the final rules land.
On/off-ramp reality (the hard part)
Moving between fiat and on-chain dollars is a regulated step that depends on a partner, not an API you host yourself:
- On-ramp (card/bank → USDC): Stripe's fiat-to-crypto onramp (https://docs.stripe.com/crypto/onramp) or another licensed provider. Your app orchestrates; the provider handles KYC and custody.
- Off-ramp to M-Pesa (Kenya-targeted projects): a licensed partner credits the recipient's M-Pesa via Daraja B2C after receiving the stablecoin.
- Your job is orchestration + reconciliation: persist every leg (Stripe PaymentIntent ID or M-Pesa
CheckoutRequestID, plus the tx hash), dedupe, and reconcile out of band. It's the same idempotency discipline as the webhooks guide.
Environment variables
Real secrets (store them in the secrets vault / Vercel env, never in the client bundle). The RPC URL carries your provider API key in its path, so treat it as a secret:
RPC_URL=https://base-mainnet.g.alchemy.com/v2/your-api-keyNon-secret settings:
| Variable | Example | Notes |
|---|---|---|
CHAIN_ID | 8453 (Base), 84532 (Base Sepolia), 1 (mainnet) | Pin it and assert the wallet matches before any write |
USDC_ADDRESS | 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 | Per chain; verify against Circle's address page |
FINALITY_CONFIRMATIONS | 3 | Raise it for high-value transfers |
SOLANA_RPC_URL | https://api.devnet.solana.com | Public devnet; use a keyed provider URL (then it's a secret) in production |
Signing keys are not env vars in production. They live in the user's wallet or a KMS/HSM. examples/wallet.ts reads a local dev key for testnet scripts only.
Security checklist
- Private keys / seed phrases never on a server, in env files, in git, or in
NEXT_PUBLIC_*. User wallets sign in the browser; app-custodied keys live in KMS/HSM. - RPC URLs and provider API keys are server-side. Proxy chain reads through your backend so keys don't ship to the client bundle.
- Assert the chain ID before any write (
getChainId/switchChain). - Always
simulateContractbeforewriteContractto catch reverts before spending gas. - Enforce a finality threshold (
waitForTransactionReceiptwithconfirmations) before treating a payment as received. - Work in the smallest unit (
bigint); useparseUnits/formatUnitsonly at the boundary. Never use JS floats for money. - Use audited token standards (OpenZeppelin) and audited contracts. Never roll your own crypto or token logic.
- Validate addresses (
isAddress) and amounts at every system boundary. A typo'd address is an irreversible loss. - Dedupe on
transactionHash + logIndexwhen indexing on-chain events (delivery is at-least-once, like webhooks). - Never ask users to sign an EIP-7702 delegation to app-controlled code. Use the wallet's vetted implementations through
wallet_sendCalls. - Test on Sepolia / Base Sepolia with faucet funds before mainnet (Holesky is gone).
codeAmani notes
- Stripe is the default rail, including for stablecoins. codeAmani is US-first. If a customer wants to pay in USDC, enable Stripe's stablecoin payment method: funds settle as USD, there's no wallet code and no key custody. Reach for direct on-chain code only when the product's core feature is on-chain.
- M-Pesa only for Kenya-targeted projects. There, don't pitch crypto as a replacement for M-Pesa. Pitch USDC as the borderless settlement rail behind an M-Pesa cash-out through a licensed partner. Daraja handles the touchpoint; the chain handles the clearing.
- Secrets server-side only.
RPC_URLand provider/custody API keys go in.env.locallocally and Vercel env vars in prod. Signing keys belong in KMS/HSM or the user's wallet, never in your code. - Regulatory posture: never issue a stablecoin, never pay yield on balances, never self-custody customer crypto. Use licensed partners and re-check the GENIUS Act final rules (effective no later than 2027-01-18).
- AI routing is unaffected. Blockchain is a settlement layer, not an AI provider, so keep Claude (primary) / OpenAI (structured) routing as-is. An agent may read chain state to answer "did this payment land?" but must never hold a signing key.
- Performance. Prefer viem over ethers/web3.js for bundle size, lazy-load the wallet-connect UI, and proxy reads server-side. For Kenya-targeted projects this matters doubly on 2G/3G Android.
- Reconciliation is a first-class job. Persist both legs (tx hash + Stripe/M-Pesa ID), dedupe, reconcile out of band, and only mark "settled" after on-chain finality and the fiat leg's confirmation.