Blockchain Integration Guide

Technology: blockchain · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/blockchain

Insight:

A blockchain is a replicated append-only ledger no single party owns. Its one real superpower is verifiable state without a trusted operator; the trilemma, gas and finality are all trade-offs around that. Reads are cheap RPC calls. Writes are key-signed, gas-costed and irreversible, so the signing key never touches your server: it lives in the user's wallet or a KMS/HSM. For codeAmani (US-first) the default way to take stablecoin money is Stripe's stablecoin payment method, which settles to USD in your Stripe balance. Build directly on chain (USDC on an L2 or mainnet, viem) only when a product truly needs it, and for Kenya-targeted projects keep M-Pesa as the last mile.

██████╗ ██╗      ██████╗  ██████╗██╗  ██╗ ██████╗██╗  ██╗ █████╗ ██╗███╗   ██╗
██╔══██╗██║     ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██║  ██║██╔══██╗██║████╗  ██║
██████╔╝██║     ██║   ██║██║     █████╔╝ ██║     ███████║███████║██║██╔██╗ ██║
██╔══██╗██║     ██║   ██║██║     ██╔═██╗ ██║     ██╔══██║██╔══██║██║██║╚██╗██║
██████╔╝███████╗╚██████╔╝╚██████╗██║  ██╗╚██████╗██║  ██║██║  ██║██║██║ ╚████║
╚═════╝ ╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝

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:

  1. 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.
  2. 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.
  3. 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."

flowchart LR
    G["Block 0 · Genesis<br/>hash: 0x9f…"] --> B1["Block 1<br/>prev: 0x9f…<br/>txs · hash: 0x3a…"]
    B1 --> B2["Block 2<br/>prev: 0x3a…<br/>txs · hash: 0x7c…"]
    B2 --> B3["Block 3<br/>prev: 0x7c…<br/>txs · hash: 0x11…"]
    B3 --> B4["Block N · pending<br/>prev: 0x11…<br/>mempool txs"]

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.

sequenceDiagram
    participant App as Your app
    participant W as Wallet / signer
    participant M as Mempool
    participant V as Validator
    participant C as Chain
    App->>W: Build tx (to, value, data)
    W->>W: Sign with private key (never leaves the wallet)
    W->>M: Broadcast signed tx
    M->>V: Validator picks txs (often highest fee first)
    V->>C: Include tx in a block
    C-->>App: 1 confirmation (could still reorg)
    C-->>App: N confirmations → final
    Note over App,C: Reads are instant & free · writes cost gas & take time

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

flowchart TD
    Q{"Who is paying, and why?"} -->|"US customer wants to pay in USDC"| S["Stripe stablecoin payments<br/>(settles to USD in Stripe balance)"]
    Q -->|"Kenya-targeted project"| M["M-Pesa / Daraja<br/>(stablecoin only behind a licensed off-ramp)"]
    Q -->|"Product feature is on-chain<br/>(wallet payouts, proofs, SIWE)"| V["Direct on-chain: viem + USDC<br/>on Base / mainnet"]
  1. 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.
  2. 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).
  3. 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 balances

The 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:

// 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:


Possible use cases for codeAmani (mapped to the existing stack)

flowchart TD
    subgraph OnChain["On-chain (settlement)"]
      U["USDC on Base / mainnet / Solana"]
    end
    subgraph Rails["codeAmani rails (existing guides)"]
      S["Stripe (default)"]
      M["M-Pesa / Daraja (Kenya projects)"]
      DB["Supabase / Neon ledger"]
      CL["Clerk auth"]
    end
    S -->|"stablecoin payments → USD balance"| U
    U <-->|"licensed off-ramp"| M
    U -->|"index events"| DB
    U -->|"SIWE alongside email/social"| CL
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)

Where a project touches stablecoins, these are the facts to plan around. Have counsel confirm before launch.


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:


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-key

Non-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


codeAmani notes

Official docs: