Blog

The Verification Phase: Why Testing Matters More When Agents Write the Code

Coding agents made writing code cheap. They didn’t make knowing the code works cheap. In her AI Engineer Code Summit talk, Lauren Tan (poteto online) explained how her team at SpaceXSI ships thousands of agent-written pull requests a month with a revert rate around half a percent. The secret isn’t the model. It’s the phase most of us still treat as an afterthought: verification.

Verification for coding agents means running the changed software, observing the behavior the change was supposed to produce, and keeping evidence a reviewer can check. It’s not the same as “the tests pass”, and it’s what lets you trust code you didn’t read line by line. This post explains that phase and what it looks like in a React Native app.

Why verification became the bottleneck

The talk, All Code Is Slop (Except Mine), has a few numbers worth remembering. Lauren shipped around 3,000 PRs in the month before the talk. Her team shipped around 11,000, with a revert rate of about 0.5%. And in 2024 she reviewed PRs from about three colleagues, while today it’s closer to 300.

Nobody can read the diffs of 300 people. Generation takes minutes now, so the cost has moved from writing code to checking it. Agents also make checking harder in specific ways:

  • They copy what they see. An anti-pattern in the codebase gets copied by the next agent, then copied again.
  • They justify their mistakes. Her team saw agents patch a bug with timers, then write comments explaining why the timers were needed. The next agent trusted the comments and added more timers.
  • They declare victory early. Anthropic saw this while building long-running coding agents: Claude marked features as done after unit tests and a few curl calls, without noticing the feature didn’t work end to end.
  • Their own tests prove little. Tests written by the agent that wrote the code encode the same misunderstanding. As the AI IDE List write-up of her workflow notes, the builder saying the tests passed adds no independent evidence.

Constrain first, then verify

Lauren’s rule is that every correction to an agent becomes a deterministic check: a lint rule, a type, or an API that makes the mistake impossible. A prompt saying “don’t do X” works sometimes. A lint rule works every time, especially when its message tells the agent what to do instead:

// eslint.config.js: stop agents from hardcoding colors in screens
export default [{
  files: ["src/screens/**/*.{ts,tsx}"],
  rules: {
    "no-restricted-syntax": ["error", {
      selector: "Property[key.name=/^(color|backgroundColor|borderColor)$/] > Literal",
      message: "Don't hardcode colors. Use a token from src/design-system/tokens.ts."
    }]
  }
}];

Every bug that’s impossible is one you don’t have to verify. Constraints shrink the problem, and verification covers what’s left.

What counts as verification

The key idea, which Lauren’s open-source pstack plugin is built around, is that a green build isn’t evidence. You have to observe the behavior that motivated the change, in the running app, and keep proof of it. The proof depends on the change:

Change type What counts as evidence
Bug fix Reproduce the bug, fix it, rerun the same reproduction
Refactor Characterization tests that stay green through each step
Performance A trace compared against a baseline. “It feels faster” doesn’t count
Visual change Screenshots diffed against approved baselines
Data change Read back the stored values and check them directly

The question to ask isn’t “did the agent test it?” It’s “what would I have to see to believe this works?” Then make the agent show you exactly that.

The test layers in a React Native app

Verification is a stack. Each layer catches different mistakes at a different cost, and the agent should run the cheap ones on every change.

Layer What it catches Typical tools
Static analysis Type errors, broken hook rules, unsafe patterns, dead code TypeScript in strict mode, ESLint with the React Hooks and React Native plugins, Knip
Unit Logic bugs in prices, reducers, validation Jest, fast-check for property-based tests
Component A screen that renders or reacts wrong React Native Testing Library
Integration Bugs between screen, store, and network Jest with the network mocked (MSW)
Contract App and API disagreeing on a payload Pact, or a schema check in CI
Design system Off-token colors, broken shared components Storybook stories, lint rules
Screenshot Unintended visual changes Image diffs on a fixed simulator
Accessibility Missing labels and roles, tiny touch targets eslint-plugin-react-native-a11y, role queries in tests, agent-device snapshots
Performance Slower renders, slower startup, dropped frames Reassure, Flashlight, React Native DevTools profiler
Dependencies Vulnerable or mismatched native packages npm audit, npx expo-doctor
End-to-end The user can’t actually finish the flow agent-device, Maestro, Detox

Static analysis is the cheapest layer and the one agents hit most often, so make it strict and run it first. TypeScript in strict mode and ESLint catch a whole class of agent mistakes before a single test runs, and Knip flags the unused files and exports agents tend to leave behind after a refactor. Reassure (from Callstack) is worth calling out too: it measures component render times and fails the PR when an agent’s change makes a screen slower, which turns “it feels faster” into a number.

Two tips make the lower layers much stronger with agents. Prefer property-based tests for core logic, because they describe intent (“the total always equals the sum of the items”) instead of mirroring the implementation. And query components by role and label in React Native Testing Library, so a missing accessibility label fails the test.

AI-driven end-to-end testing

End-to-end is where AI changes verification the most. Lauren’s team lets agents run the app and hand back screenshots and videos instead of claims. On React Native, two tools cover this.

agent-device is Callstack’s CLI that lets a coding agent drive iOS and Android apps. The agent reads an accessibility snapshot, acts on elements by ref, and sees what changed:

agent-device open ShopApp --platform ios
agent-device snapshot -i
# @e4 [button] "Remove Coffee"
agent-device press @e4 --settle
# + @e9 [text] "Your cart is empty"
agent-device screenshot ./evidence/cart-empty.png
agent-device close

The agent gets a description of the screen, not just pass or fail, so it can notice on its own that the empty state never appeared. Because the snapshot comes from the accessibility tree, an unlabeled button shows up right away.

Maestro keeps what the agent learned. Once the fix is verified, the agent saves the path it took as a flow and commits it with the PR, so CI replays it on every future change, with no LLM involved:

# .maestro/cart-remove-last-item.yaml
appId: com.example.shop
---
- launchApp:
    clearState: true
- startRecording: cart-remove-last-item
- tapOn: "Add to cart"
- tapOn:
    id: "cart-tab"
- tapOn: "Remove Coffee"
- assertVisible: "Your cart is empty"
- takeScreenshot: cart-empty
- stopRecording

The AI does the expensive, exploratory part once. The deterministic tool keeps the result forever. Agents also help write flows from a plain-language description, fix flows when a label changes, and read failed runs to tell a real bug from a flaky wait. Lauren’s team goes further: on every release, an agent uses the app, hunts for bugs, and opens fix PRs.

The same lesson from Anthropic’s long-running agents

Anthropic reached the same conclusion from a different direction. In Effective harnesses for long-running agents, Justin Young describes agents building a full web app across many sessions. What fixed premature “done” wasn’t a better prompt about quality. It was giving the agent browser automation and telling it to “do all testing as a human user would.” That change dramatically improved results, because the agent found bugs that weren’t visible from the code. agent-device plays the same role on mobile.

Three ideas from that harness carry over directly to a React Native project:

  • A feature list as the definition of done. Every feature starts as failing, and the agent may only flip it to passing after testing it end to end. Verification becomes the gate, not a step the agent can skip.
  • A smoke test at the start of every session. Before touching anything, the agent launches the app and runs one basic flow. If the last session left the app broken, it gets caught before new work piles on top. A single Maestro flow is a perfect fit here.
  • Your tools’ blind spots become bug hotspots. Claude couldn’t see browser-native alert dialogs, and features that relied on them ended up buggier. On mobile, check what your tooling can see: native alerts, permission prompts, and system sheets are where agent-verified features fail quietly.

The human in the loop

Automated checks answer “does it work?” They’re weak at “is it good?” That’s why verification has to produce artifacts that both an AI and a human can review:

  • videos of the end-to-end flows
  • screenshots in light mode, dark mode, and large text, plus diffs against baselines
  • accessibility snapshots showing what a screen reader will announce
  • logs from Metro, the device, and the app
  • performance traces for startup, scrolling, and key flows
  • observability data, like crash and error reports from staging builds
  • reports from every test layer

A verifier agent with fresh context reviews the evidence first. It checks that the video shows the fixed behavior, the logs have no new errors, and the screenshot diffs only touch the screens the task mentioned. Then a human reviews what needs judgment: visual quality, accessibility with VoiceOver or TalkBack, performance against the baseline, and whether the change solves the user’s problem.

Lauren describes the shift directly:

“our code review process has now really shrunk into looking at verification artifacts instead” Lauren Tan, All Code Is Slop (Except Mine)

The diff is still there, but it’s no longer where trust comes from. Two rules keep this honest: the agent that wrote the code is never the only one who verifies it, and any new commit means verifying again.

The verification phase, organized

Verification phase workflow for coding agents: a task with a feature list starts with a smoke test, then static analysis, the test layers, and accessibility and performance checks lead to AI-driven end-to-end tests with agent-device, which are saved as Maestro flows. Screenshot tests and observability feed an evidence bundle that a verifier agent and then a human review before merge, with findings looping back to the agent.

  1. Constrain. Lint rules, types, and architecture make whole classes of bugs impossible.
  2. Run the fast tests. Unit, component, integration, contract, and design system tests on every change.
  3. Verify on a real app. The agent starts with a smoke test, drives the change with agent-device, then saves the path as a Maestro flow.
  4. Collect evidence. Videos, screenshots, accessibility snapshots, logs, traces, and observability data go on the PR.
  5. Review by AI, then by a human. A verifier agent checks the evidence. A human judges visuals, accessibility, and performance.
  6. Merge, or loop back. Findings go back to the agent, and a new commit means verifying again.

Lauren warned that automating this loop before the codebase is in good shape just produces more slop, faster. Her team spent months on constraints and verification before letting agents merge most of their own PRs. That’s the order that works: earn the trust first, then hand over the autonomy.

For the mobile side of this, I also wrote about why coding agents struggle with mobile, and the harness that fixes it, and about verifying AI-written code in practice.

References


Solidity Fundamentals: A Practical Guide for 0.8.x

Solidity is the main language for writing smart contracts on Ethereum and other EVM chains. This guide covers the fundamentals you need for Solidity 0.8.x: how a contract is laid out, value and reference types, data locations, mappings, events and errors, how gas is charged, the difference between a call and a transaction, the global variables you’ll reach for, and how inheritance works. Every example compiles with the 0.8 compiler.

Between 2017 and 2020 I wrote nine short posts on these topics. A lot changed since then: now and msg.gas are gone, arithmetic overflow reverts by default, Ethereum moved to proof of stake, and fees work differently after EIP-1559. So I merged them into this one guide and brought everything up to date. The old URLs redirect here.

How the EVM runs your code

Solidity doesn’t run directly. The compiler (solc) turns it into bytecode, a list of low-level instructions (opcodes) for the Ethereum Virtual Machine. Every Ethereum node runs the same EVM, which is why every node reaches the same result for the same transaction. Clients implement it in several languages: Geth in Go, Nethermind in C#, Besu in Java and Reth in Rust, among others.

Diagram of the Ethereum Virtual Machine executing smart contract bytecode

A few properties of the EVM explain a lot of Solidity’s design:

  • It’s a stack machine with 256-bit words. That’s why uint256 is the “natural” integer size, and why smaller types don’t always save gas.
  • Each opcode has a fixed gas cost. Writing to storage is by far the most expensive thing you can do.
  • A contract has several places to keep data: storage (persistent, on chain), memory (temporary, wiped after the call), calldata (the read-only input of the call) and the stack. Since the Cancun upgrade there’s also transient storage, which lives only for the duration of a transaction.

The EVM page on ethereum.org goes deeper if you’re curious about opcodes and the execution model.

Anatomy of a contract

A contract is a bit like a class: it groups state, functions and types. Here’s a small but complete one. I’ll refer back to it in the rest of the guide.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract TipJar {
    // State variables live in storage
    address public immutable owner;
    uint256 public constant MIN_TIP = 0.001 ether;

    struct Tip {
        address from;
        uint256 amount;
        string message;
    }

    Tip[] private tips;
    mapping(address tipper => uint256 total) public totalByTipper;

    event TipReceived(address indexed from, uint256 amount, string message);
    error TipTooSmall(uint256 sent, uint256 minimum);
    error NotOwner();
    error WithdrawFailed();

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    constructor() {
        owner = msg.sender;
    }

    function tip(string calldata message) external payable {
        if (msg.value < MIN_TIP) revert TipTooSmall(msg.value, MIN_TIP);
        tips.push(Tip(msg.sender, msg.value, message));
        totalByTipper[msg.sender] += msg.value;
        emit TipReceived(msg.sender, msg.value, message);
    }

    function tipCount() external view returns (uint256) {
        return tips.length;
    }

    function withdraw() external onlyOwner {
        (bool ok, ) = payable(owner).call{value: address(this).balance}("");
        if (!ok) revert WithdrawFailed();
    }
}

The parts, from top to bottom:

  • SPDX license line and pragma: the license is metadata, and pragma solidity ^0.8.24 means “any 0.8 compiler from 0.8.24 up”.
  • State variables: owner, tips and totalByTipper are stored on chain. constant values are inlined at compile time and immutable values are set once in the constructor. Neither one uses a storage slot, so reading them is cheap.
  • Struct: Tip groups related fields into a custom type.
  • Mapping: totalByTipper is a key-value store (more on mappings below).
  • Event and errors: TipReceived is for off-chain listeners, and the custom errors describe why a call reverted.
  • Modifier: onlyOwner wraps a function with a check. The _; marks where the function body runs.
  • Constructor: runs once, at deployment.
  • Functions: tip accepts Ether because it’s payable, tipCount only reads state because it’s view, and withdraw sends Ether out.

Types

Solidity is statically typed, so every variable’s type is known at compile time.

Value types

Type What it holds
bool true or false
uint8 … uint256 Unsigned integers in steps of 8 bits. uint is an alias for uint256.
int8 … int256 Signed integers. int is an alias for int256.
address A 20-byte Ethereum address
address payable An address you can send Ether to
bytes1 … bytes32 Fixed-size byte arrays
enum A user-defined set of named constants

Two things changed in 0.8 that matter every day:

  • Arithmetic is checked. Overflow and underflow revert instead of silently wrapping around. That’s why you rarely see SafeMath in new code. When you’re sure a value can’t overflow and you want to save gas, wrap it in an unchecked { ... } block.
  • ** is the power operator. 2 ** 8 is 256. ^ is bitwise XOR, which is an easy mistake if you come from other languages (my 2017 post got this wrong).

Reference types

string, bytes (a dynamic byte array), arrays (uint256[], address[10]), structs and mappings are reference types. For these you have to say where the data lives, which brings us to data locations.

Data locations: storage, memory and calldata

Every reference-type variable has a location:

  • storage: persistent contract state. State variables are always in storage.
  • memory: a temporary copy that disappears when the function returns.
  • calldata: the read-only input of an external call. It’s the cheapest option for parameters you don’t modify.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Locations {
    uint256[] public numbers;

    function addAll(uint256[] calldata input) external {
        for (uint256 i = 0; i < input.length; i++) {
            numbers.push(input[i]);
        }
    }

    function doubled() external view returns (uint256[] memory result) {
        result = new uint256[](numbers.length);
        for (uint256 i = 0; i < numbers.length; i++) {
            result[i] = numbers[i] * 2;
        }
    }

    function resetFirst() external {
        uint256[] storage ref = numbers; // a pointer to storage, not a copy
        ref[0] = 0;
    }
}

The behavior that trips people up: assigning storage to a memory variable copies the data, so changes to the copy don’t touch the contract state. Assigning it to a storage variable creates a reference, so changes do. Since 0.5.0 you must write the location explicitly for reference-type parameters and local variables, so the compiler won’t let you guess. (Older tutorials, including mine, say local variables default to storage. That hasn’t been true for years.)

Mappings

A mapping is Solidity’s hash table:

mapping(address user => uint256 balance) public balances;
mapping(address owner => mapping(address spender => uint256 amount)) public allowance;

The named keys and values (user, balance) are optional and were added in 0.8.18. They make code and generated getters easier to read.

Mappings behave differently from a dictionary in most languages:

  • Every key exists. A key that was never set returns the type’s zero value (0, false, address(0)). You can’t tell “set to zero” apart from “never set” without tracking it yourself.
  • No length and no iteration. The keys aren’t stored, only the hashed slots. If you need to list entries, keep a separate array of keys alongside the mapping.
  • Storage only. You can’t create a mapping in memory or pass one to an external function.
  • Nesting works, as the ERC-20 allowance above shows.
  • A public mapping gets an automatic getter that takes the key as an argument.

Looping over large arrays costs gas on every iteration and can hit the block gas limit. So the usual pattern is: write to a mapping for lookups, emit an event for history, and let off-chain code (an indexer, or your app) build lists from those events.

Events and custom errors

Events write data to the transaction’s logs. They’re cheap compared to storage, and apps and indexers can subscribe to them. Contracts can’t read logs, so events are only for the outside world.

event Transfer(address indexed from, address indexed to, uint256 value);
emit Transfer(msg.sender, to, amount);

Up to three parameters can be indexed, which makes them filterable (for example, “all transfers to this address”).

Custom errors, added in 0.8.4, are the modern way to revert:

error InsufficientBalance(uint256 available, uint256 required);

if (balance < amount) revert InsufficientBalance(balance, amount);

They’re cheaper than require(condition, "long message") because the error is encoded as a 4-byte selector plus its arguments instead of a string. Your app can also decode them and show a meaningful message. You’ll still see require a lot, and since 0.8.26 it also accepts a custom error as its second argument.

Functions: visibility and state mutability

Visibility

Visibility Who can call it
external Only from outside (other contracts, transactions). Inside the contract you’d need this.f().
public From anywhere. For state variables, the compiler generates a getter.
internal This contract and contracts that inherit from it. This is the default for state variables.
private Only this contract. Not even derived contracts.

private doesn’t mean secret. Everything in storage is readable by anyone running a node, so never put passwords or keys in a contract.

State mutability

  • view: reads state but doesn’t change it.
  • pure: neither reads nor changes state (calculations, encoding).
  • payable: can receive Ether with the call. Functions without it revert if Ether is sent.
  • No keyword means the function can change state.

Calls vs transactions

There are two ways to run a contract function from outside the chain, and they’re very different.

A call (eth_call in JSON-RPC) runs the function on the node you’re connected to and returns the result right away. Nothing is signed, nothing is broadcast and nothing is saved, so it costs you nothing. You use it to read data, for example tipCount().

A transaction is signed by an account, broadcast to the network, included in a block by a validator and executed by every node. It can change state, it costs gas, and you don’t get the function’s return value back directly. You read the outcome from the receipt and its events. You use it for anything that writes, like tip().

Inside the EVM, when one contract calls another, that’s a message call. It runs as part of the same transaction and shares its gas.

One nuance: a view function is only free when you call it off chain. If a transaction calls it as part of other work, its execution costs gas like any other code.

Gas, gas price and fees

Gas measures how much computation and storage a transaction uses. It’s a unit of work, not a currency. You pay for it in ETH.

Since the London upgrade (EIP-1559, in 2021), the fee works like this:

fee = gas used × (base fee + priority fee)
  • The base fee is set by the protocol and goes up or down with network demand. It’s burned, not paid to anyone.
  • The priority fee (the “tip”) goes to the validator who includes your transaction.
  • You also set a gas limit (the most gas you’ll allow) and a max fee per gas (the most you’ll pay per unit). If the base fee spikes above your max fee, the transaction just waits.

If a transaction reverts, its state changes are undone, but it still lands in a block and you still pay for the gas used up to that point. If it runs out of gas, you pay for the whole gas limit.

Writing cheaper contracts

The habits that make the biggest difference:

  • Touch storage as little as possible. Writing a new non-zero value to a storage slot costs about 20,000 gas, while memory operations cost a handful. Read a storage value once into a local variable if you use it several times.
  • Use constant and immutable for values that don’t change.
  • Pack small variables. Storage is organized in 32-byte slots, and variables declared next to each other share a slot if they fit (for example uint128 a; uint64 b; uint64 c;).
  • Use calldata for external function parameters you only read.
  • Use custom errors instead of long revert strings.
  • Keep contracts under the 24 KB size limit (EIP-170) by splitting logic or using libraries.

Global variables

These are always available. I’ve noted the ones that changed since older tutorials.

Variable Meaning
msg.sender The address that made the current call
msg.value Wei sent with the call
msg.data The complete calldata
msg.sig The first 4 bytes of the calldata (the function selector)
block.number The current block number
block.timestamp The block timestamp in seconds. Replaces now, which was removed in 0.7.0.
block.chainid The chain ID (1 for Ethereum mainnet)
block.basefee The current base fee (since EIP-1559)
block.prevrandao Randomness from the beacon chain. Replaces block.difficulty, which no longer means anything after the move to proof of stake.
block.coinbase The address of the block’s fee recipient
block.gaslimit The block’s gas limit
blockhash(n) The hash of one of the 256 most recent blocks. It used to be block.blockhash.
gasleft() Remaining gas. Replaces msg.gas, which was removed in 0.5.0.
tx.origin The account that started the transaction
tx.gasprice The gas price of the transaction

Two warnings. Don’t use tx.origin for authorization. If your contract checks tx.origin == owner, a malicious contract the owner interacts with can call yours and pass the check. Use msg.sender. And don’t treat block.timestamp or block.prevrandao as a secure source of randomness for anything valuable. Validators have some influence over both. Use a verifiable randomness service such as Chainlink VRF. Oracles like Chainlink are also how a contract gets any off-chain data; I used them in my Nomad Token hackathon project.

Hashing and type conversion

keccak256

keccak256 takes a single bytes argument and returns a bytes32 hash. To hash several values, encode them first:

bytes32 id = keccak256(abi.encode(user, nonce));

abi.encodePacked gives a shorter encoding, but with two or more dynamic types (like two strings) different inputs can produce the same bytes: ("ab", "c") and ("a", "bc") collide. Prefer abi.encode unless you know why you need packed encoding.

Converting between types

Implicit conversions happen only when no information can be lost. A uint8 fits in a uint256, so this compiles:

uint8 small = 8;
uint256 big = small;

Going the other way needs an explicit conversion, and it silently cuts off the higher-order bits:

uint32 a = 0x12345678;
uint16 b = uint16(a); // 0x5678

Since 0.8.0, an explicit conversion can change only one thing at a time: sign, size or kind of type. uint16(int8(x)) doesn’t compile because it changes both sign and size. You have to go through an intermediate type, for example uint16(uint8(x)), which makes the risk visible in the code.

Address conversions follow the same idea: address(uint160(value)) turns a number into an address, and payable(addr) turns an address into an address payable.

Inheritance

A contract inherits from others with is. When you deploy it, the compiler copies the code from every parent into one contract with one address. Calls to parent functions are just internal jumps.

A function must be marked virtual to be overridable, and the overriding function must say override:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Grandparent {
    function who() public pure virtual returns (string memory) {
        return "Grandparent";
    }
}

contract Parent is Grandparent {
    function who() public pure virtual override returns (string memory) {
        return "Parent";
    }
}

contract Uncle is Grandparent {
    function who() public pure virtual override returns (string memory) {
        return "Uncle";
    }
}

contract Child is Parent, Uncle {
    function who() public pure override(Parent, Uncle) returns (string memory) {
        return super.who(); // "Uncle"
    }
}

With multiple inheritance, order matters. List parents from “most base-like” to “most derived”. Solidity linearizes the hierarchy (using C3 linearization, like Python), and super calls the next contract in that order, not necessarily the parent you expect. For Child is Parent, Uncle, the order from most derived is Child, Uncle, Parent, Grandparent, so super.who() returns "Uncle". When a function exists in more than one parent, you have to list them all in override(Parent, Uncle).

A few more rules:

  • A child can use everything that isn’t private: internal and public state and functions.
  • An abstract contract has at least one function without an implementation and can’t be deployed on its own.
  • An interface only declares external functions. It’s what you use to call another contract when you don’t have its source code, for example IERC20(token).transfer(to, amount).

In practice you’ll mostly inherit from audited libraries like OpenZeppelin Contracts instead of writing token logic or access control yourself.

Where to go next

To try any of these examples, paste them into Remix, which runs in the browser. For real projects, use Foundry or Hardhat. Truffle, which my older posts used, was retired in 2023.

The official Solidity documentation is the reference for everything here, and its list of breaking changes per version explains why older code doesn’t compile anymore. If you build on Android, I also wrote about how to integrate an Android app with an ERC-20 smart contract.


Ethereum Token Standards Explained: ERC-20, ERC-721, ERC-1155 and ERC-777

A token standard is an agreed set of functions and events that a smart contract implements so wallets, exchanges and other contracts can work with it without custom code. On Ethereum, four standards cover most of what you’ll meet: ERC-20 for fungible tokens, ERC-721 for non-fungible tokens (NFTs), ERC-1155 for contracts that hold many token types at once, and ERC-777, an attempted successor to ERC-20 that’s now discouraged. This guide explains what each one does, how they differ, and which to pick.

I wrote about ERC-1155 in 2018 and ERC-777 in 2019, when both were new. Some of what I wrote then didn’t hold up (ERC-1155 isn’t backward compatible with ERC-20, and ERC-777 turned out to be risky), so I replaced both posts with this comparison. The old URLs redirect here.

Fungible vs non-fungible

A token is fungible when every unit is interchangeable. One USDC is the same as any other USDC, just like one dollar bill is as good as another. What matters is the amount.

A token is non-fungible when each unit is unique. A concert ticket for seat 14B isn’t the same as one for seat 30F, even though both are for the same show. What matters is which token you own, identified by a token ID.

Some tokens sit in between: 500 copies of the same in-game sword are interchangeable with each other but different from a shield. That “semi-fungible” case is where ERC-1155 shines.

ERC-20: fungible tokens

ERC-20 is the original and still the most widely used standard. Stablecoins, governance tokens and wrapped ETH (WETH) are all ERC-20. Each token type lives in its own contract, which tracks a balance per address.

The interface is small:

Function or event Purpose
totalSupply() Total tokens in existence
balanceOf(account) Balance of an address
transfer(to, amount) Send your own tokens
approve(spender, amount) Allow another address to spend up to amount of yours
allowance(owner, spender) How much spender may still spend
transferFrom(from, to, amount) Spend tokens you were approved for
Transfer, Approval events Let wallets and indexers track changes

The approve + transferFrom pair is how contracts take payment: you approve a DEX or a lending protocol, then it pulls the tokens when you trade or deposit. It’s also the biggest source of user losses, because people approve unlimited amounts to contracts that later get exploited. Two habits help: approve only what’s needed, and support EIP-2612 permit, which lets users approve with an off-chain signature instead of a separate transaction.

Another gotcha: plain transfer to a contract that doesn’t expect tokens just leaves them stuck there. Nothing in ERC-20 asks the recipient whether it can handle them.

With OpenZeppelin Contracts, a basic token takes a few lines:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";

contract MyToken is ERC20, ERC20Permit {
    constructor() ERC20("My Token", "MTK") ERC20Permit("My Token") {
        _mint(msg.sender, 1_000_000 * 10 ** decimals());
    }
}

decimals() defaults to 18, so balances are stored as integers scaled by 10^18. One token is 1e18 units. Forgetting this is the most common bug when an app displays balances.

ERC-721: non-fungible tokens

ERC-721 is the NFT standard. One contract holds a whole collection, and each token has a unique tokenId with exactly one owner:

  • ownerOf(tokenId) returns the owner, and balanceOf(owner) counts how many tokens they hold.
  • safeTransferFrom(from, to, tokenId) transfers a token. If the recipient is a contract, it must implement onERC721Received, otherwise the transfer reverts. This fixes ERC-20’s stuck-tokens problem.
  • approve(to, tokenId) approves one token, and setApprovalForAll(operator, true) approves an operator (like a marketplace) for the whole collection.
  • The optional metadata extension adds tokenURI(tokenId), which points to JSON with the name, image and attributes, usually stored on IPFS or a server.

ERC-1155: many token types in one contract

ERC-1155 lets one contract manage any number of token types, each identified by an id. Each id can be fungible (mint a million units), non-fungible (mint exactly one) or anything in between. It was designed for games, where one contract might hold gold coins, potions and unique legendary items.

What it changes compared with deploying one ERC-20 and one ERC-721 per asset:

  • Balances are per account and per id: balanceOf(account, id).
  • Batch operations. safeBatchTransferFrom moves several token types in one transaction, and balanceOfBatch reads several balances in one call. That saves a lot of gas when a player trades five items at once.
  • One deployment for everything, instead of a contract per token.
  • Mandatory receiver hooks. Transfers to a contract call onERC1155Received (or the batch version), so tokens can’t get stuck in contracts that don’t support them.
  • Operator-only approvals. There’s setApprovalForAll but no per-token approve.
  • Metadata by template. uri(id) can return one URL with an {id} placeholder that clients replace with the token’s hex id.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SWORD = 1;
    uint256 public constant CROWN = 2;

    constructor() ERC1155("https://example.com/items/{id}.json") {
        _mint(msg.sender, GOLD, 1_000_000, "");  // fungible
        _mint(msg.sender, SWORD, 500, "");       // semi-fungible
        _mint(msg.sender, CROWN, 1, "");         // unique
    }
}

The trade-off is compatibility. An ERC-1155 token isn’t an ERC-20 or ERC-721 token (my 2018 post said otherwise, and that was wrong). Wallets and DeFi protocols that only speak ERC-20 can’t use it directly, so a fungible ERC-1155 id won’t show up in a DEX without a wrapper.

ERC-777: the one to avoid

ERC-777 tried to improve ERC-20 while staying backward compatible. It added operators (addresses allowed to send on your behalf) and hooks: before tokens leave an account, a tokensToSend function can run, and when tokens arrive, a tokensReceived function runs on the recipient. Hooks are registered through the ERC-1820 registry contract. The idea was to send tokens and notify a contract in a single step, without the approve-then-transfer dance.

In practice the hooks caused real damage. Because the recipient’s code runs in the middle of a transfer, ERC-777 tokens opened reentrancy holes in contracts written with ERC-20 assumptions. In 2020, attackers used ERC-777 hooks to drain the imBTC pool on Uniswap V1 and about $25 million from the lending protocol Lendf.Me.

OpenZeppelin removed its ERC-777 implementation in Contracts 5.0. Don’t use it for new tokens. If you need “transfer and call” behaviour, approve-plus-call patterns, permit signatures or ERC-1363 are safer options, and if you integrate with arbitrary tokens, protect your contract against reentrancy anyway.

Which one should you use?

You want to… Use
Create a currency, governance or reward token ERC-20 (add permit)
Create a collection of unique items ERC-721
Manage many item types, including unique and fungible ones, with batch transfers ERC-1155
Add hooks or “send and notify” to a fungible token Not ERC-777. Look at ERC-1363 or a separate contract call.

Whatever you pick, start from an audited implementation like OpenZeppelin Contracts rather than writing token logic yourself. The original specs are worth reading too: EIP-20, EIP-721 and EIP-1155.

If the Solidity in the examples is new to you, start with my Solidity fundamentals guide. To read token balances from a mobile app, see how to integrate an Android app with an ERC-20 token.


Why Coding Agents Struggle With Mobile, and the Harness That Fixes It

Coding agents are great at producing code that looks finished. On mobile, looking finished tells you very little. An app can compile and still crash at launch, hide a button behind the keyboard, or lose its state on rotation. You find those bugs by running the app, and that’s where a typical agent setup goes blind. The fix probably isn’t a smarter model. It’s a better harness around the one you already have.

Why do coding agents struggle with mobile?

Coding agents struggle with mobile because proof that the code works is slow and expensive to get. Most agent workflows assume a fast, cheap feedback loop: edit a file, run a test, read the result. Mobile breaks that assumption in a few ways.

  • The build is slow and complicated. Gradle, JDK versions, the Android SDK, and signing all fail in their own ways, often far from the line the agent just changed.
  • The truth lives on a device. Layout, navigation, permissions, and lifecycle bugs only show up at runtime, usually behind several steps of UI.
  • The environment fails too. An emulator that didn’t boot looks a lot like a broken app. If the agent can’t tell them apart, it starts “fixing” code that was never wrong.

That list is my own experience talking. I couldn’t find a study that directly compares agents on mobile and backend work, and I’d be careful with anyone who claims a number for it. But two recent preprints do show what helps once you’re working on mobile.

What research says about agents on Android

Automating Android Build Repair by Son et al. (revised April 2026) tested agents on AndroidBuildBench, a set of 1,019 real build failures from 43 open source Android projects. The authors swapped the general shell for a few Android-specific tools, such as run_build and change_java_version. With a budget of 30 model calls, shell-only access fixed 54.3% of failures on the first try. The full set of domain tools reached 74.0%. Same job, better tools. The authors also report that larger code changes were more likely to fail, and they suggest building often after small changes.

AppEval by Xie et al. (August 2026) asks agents to repair Android apps, and a task only counts as solved when a hidden test passes in the installed app. First-try pass rates across five agent and model setups ranged from 22% to 90.5% on the same 200 tasks, even though the median reference fix was just two lines. The benchmark also logs build, install, launch, and timeout problems as infrastructure errors, so they don’t get mistaken for program failures.

One caveat: neither paper isolates how much test feedback itself improves an agent. They’re evidence for better tools and for judging agents at runtime. The harness below is my reading of that evidence, plus what I learned building No Middleman.

A seven-step harness for mobile coding agents

Think of it as a proving ground. The agent gets to drive as fast as it likes, but every lap ends at a checkpoint it can’t talk its way past.

Mobile agent harness workflow: a signed test, maker agent, fast gates, device check, device UI tests, checker agent, and a draft pull request, with failures looping back to the maker

1. Narrow the tools. Give the agent build, test, and install commands that do one thing. Don’t make it work out the right shell incantation on every run.

2. Write the test first. A human approves an acceptance test before the agent writes any code. That test defines “done”, so the agent can’t renegotiate it halfway through.

3. Order the checks from cheap to expensive. Run lint, unit tests, and the build before touching a device. A broken import should cost seconds, not a five-minute UI run.

4. Make device runs cheap. Reset the emulator to a known state and only recompile native code when native inputs change. No Middleman does this by caching its dev client against a hash of those inputs, so a real device test can sit inside the loop.

5. Report failures honestly. Tell the agent whether its code failed or the environment did. A few exit codes get you most of the way there:

#!/usr/bin/env bash
# 0 = passed, 1 = code failure (fix it), 2 = infrastructure failure (don't touch the code)
./gradlew lint testDebugUnitTest assembleDebug || exit 1

timeout 60 adb wait-for-device || exit 2
[ "$(adb shell getprop sys.boot_completed | tr -d '\r')" = "1" ] || exit 2

./gradlew connectedDebugAndroidTest || exit 1

It’s only a sketch, since a missing SDK would still come back as a code failure. But an agent that sees 2 can stop and ask for help instead of rewriting a working screen.

6. Separate the maker from the checker. A green run isn’t the finish line. A second agent that never touched the code reviews the diff for weakened assertions, meaningless mocks, and masked timing problems. Tests can get stricter during the loop, never looser.

7. Stop at a pull request. Set hard limits on iterations and time, and always end with a draft PR, even when the budget runs out. A person still decides what merges.

Where to start

You don’t need all seven on day one. I’d start with the exit codes and one acceptance test on a real emulator, because those two change what the agent can actually see. If you want to go deeper, I’ve written about designing the control loop behind autonomous agents, how No Middleman verifies AI-written code, and how to test autonomous AI agents.

An agent that can’t see the running app is guessing. So before you switch models, check what your agent is able to observe. On mobile, that’s probably where the biggest gain is hiding.


Jev: A Decision Model for the Boring, Important Parts of Your Pipeline

Most of the LLM calls I’ve put in production aren’t really asking the model to write anything. They’re asking it to decide: is this ticket urgent, which bucket does this PR belong in, does this comment need a reply. Jev, the first model from TypeSafe AI, is built for exactly that kind of call. It doesn’t generate text at all. It returns typed values, and after reading through the Jev 1.14 release notes and Claire Vo’s beginner episode on it, I think it’s worth a closer look for anyone building agents or data pipelines.

Line-art eye with radiating rays and sparkles on a pink background, illustrating Jev as a decision model

What Jev actually is

TypeSafe calls Jev a System One Model. The name borrows from the fast, intuitive half of Kahneman’s thinking model, and the idea is that a lot of software needs quick judgment calls, not essays. TypeSafe spent about two years in stealth building it and describes the company as building “machine-native intelligence infrastructure for automation.”

The API shape is simple. You send a state (your data, as text or JSON) and a set of named questions. Each question has a type, and Jev answers all of them in parallel against the same state. According to the Jev docs, there are three main question types:

  • choice: pick one label from a list you define. Returns the choice, per-label probabilities, and a confidence.
  • score: rate the state on an ordered rubric, lowest to highest. Returns a score, probabilities, and confidence.
  • noul: is this statement true? Returns a single number between 0 and 1.

Because each question is evaluated independently, adding more questions to one request barely changes latency. That’s a nice property. You can ask “which department?”, “how frustrated is the customer?” and “is this urgent?” in a single round trip.

Here’s roughly what a request looks like, based on the schema in the quick start guide:

curl https://api.typesafe.ai/v1/systemone \
  -H "Authorization: Bearer $TYPESAFE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "jev-latest",
    "state": "The app crashes every time I open settings. Third time reporting this!",
    "questions": {
      "department": {
        "type": "choice",
        "instructions": "Which team should handle this ticket?",
        "criteria": {
          "billing": "Payments, invoices, refunds",
          "technical": "Bugs, crashes, performance"
        }
      },
      "frustration": {
        "type": "score",
        "instructions": "How frustrated is the customer?",
        "criteria": ["Calm", "Annoyed", "Very frustrated"]
      },
      "is_urgent": {
        "type": "noul",
        "instructions": "This ticket needs a response today."
      }
    }
  }'

The response comes back keyed by your question IDs, each with its typed answer and probabilities, plus token usage. There’s no parsing of free text, no “please respond in JSON” prompt, and no retry loop for malformed output. There are official SDKs too (pip install typesafe-sdk and npm install @typesafe-ai/sdk) if you’d rather not hand-roll HTTP.

Why it’s interesting: the price

The number that got my attention came from Claire Vo’s How I AI episode on Jev for beginners. Jev costs 4 cents per million input tokens, and there’s no output charge. Since the output is just a handful of numbers and labels, that’s most of the bill.

At that price, classification stops being something you budget for. Vo ran Jev over 1,700 pull requests for 9 cents and used pairwise clustering to see where her engineering time was actually going. That’s a task I’d normally skip because it isn’t worth a few dollars of GPT calls plus the time spent cleaning up the outputs. At 9 cents, you just do it.

What people are building with it

The examples from the episode are a good map of where a decision model fits:

  • PR categorization: the 1,700 PRs above, grouped into themes to show where effort went.
  • Personal meta-analysis: running Jev over your own local Claude Code and Codex sessions to see patterns in how you work with agents.
  • Gmail triage: Jev scores incoming email, and a regular LLM drafts the follow-ups only for the ones that matter.
  • Product insights graph: in ChatPRD, 1,100 signals turned into around 200,000 classifications.
  • Audience dashboard: a searchable dashboard built from 4,500 YouTube comments for close to nothing.
  • Voice-to-color emotion app: a real-time demo pairing Jev with the OpenAI Realtime Voice API.

The pattern across all of them is the same. Jev handles the high-volume scoring, routing and labeling. A general-purpose LLM handles anything that needs words. Vo mentions she doesn’t really use Jev alone anymore, and that matches how I’d use it. It’s a cheap, fast filter in front of an expensive model, not a replacement for one.

If you’ve read my post on designing the control loop behind autonomous agents, this is the “should I keep going?” and “which tool next?” kind of decision. Having those come back as a typed value with a probability attached makes termination conditions and routing a lot easier to reason about than parsing a sentence.

What’s new in Jev 1.14

TypeSafe published the Jev 1.14 release notes on October 14, 2026, framed around two audiences: builders who need production reliability, and dreamers who want to experiment. Their answer is a set of “danger zone” flags. Experimental features sit behind API headers, so you have to opt in explicitly, and TypeSafe is clear that they aren’t ready for production.

Composable images (danger zone)

It turns out Jev 1.13 was already multimodal, it just wasn’t advertised. Now you can add images through a find-and-replace in assets, and reference them in state, instructions or criteria. Turn it on with:

TypeSafe-Danger-Zone-Images: true

TypeSafe’s own advice is worth repeating: every model, Jev included, does worse on multimodal input than on pure text. Break your questions into the simplest pieces you can.

The new box type

This one is only enabled for jev-1.14.0. It returns a single bounding box, and it’s the first output type that isn’t just a smarter if statement. I read it as a hint about where System One models are heading: still typed and constrained, but answering more than “which one?” or “how much?”.

Longer context (danger zone)

Jev can handle more context than the production limit allows. TypeSafe capped it on purpose because reliability drops on long inputs. You can lift the cap with:

TypeSafe-Danger-Zone-Long-Context: true

They still recommend keeping context short, and honestly that’s good advice for any classifier. If the decision depends on 50 pages of input, it’s probably more than one decision.

Model aliases and deprecation

  • jev-1.14.0 is available now under the jev-preview alias. Improvements are small and broad, with multilingual support expected to gain the most.
  • jev-latest moves to 1.14.0 one week after the announcement.
  • jev-1.13.0 stays around for a while. The notice gives 60 days for 1.13.0 and 30 days for 1.14.0, with a formal deprecation policy promised before that kicks in.

If you’re in production, pin a version. Pointing a pipeline at jev-latest and letting a model swap happen under you is a classic way to get a silent shift in your label distribution.

Opt-in data sharing and an internal benchmark

You can now opt in to let your queries help TypeSafe find model weaknesses. They say they still won’t train on your queries. They also shared an internal estimate of developer-relevant intelligence, with a lot of caveats: it compares only open-weight models, the methodology will change, and it’s probably biased toward Jev. Their own advice is to trust your evals over theirs, which I appreciate.

Should you try it?

If you have a pipeline where an LLM is being used as a glorified when expression, yes, probably. Ticket routing, content moderation, lead scoring, log triage, agent routing. Those are the places where typed outputs and near-zero cost add up fast.

I’d start small. Pick one classification step you already run with a general LLM, write the same questions as Jev choice or score types, and compare the outputs on a few hundred real examples. Look at the confidence values too. Low-confidence answers are a natural place to hand off to a bigger model or a human.

And I’d leave the danger zone headers alone in anything that matters, at least for now. TypeSafe is telling you they’re rough, and it’s nice when a vendor says that out loud.