# How to Build a dApp in 2026: Architecture, Stack, Timeline and Cost

> A step-by-step guide to building a decentralized app: what goes on-chain, a tested Solidity contract, deployment, a web front end, indexing, and realistic timelines and costs.

- Author: OnChain Team
- Published: 2026-10-14
- Page: https://www.onchain.ro/blog/how-to-build-a-dapp

Building a dApp comes down to six steps: decide what must live on-chain, write and test the smart contract, deploy it to a testnet, build a web front end that reads and writes to it, index its events for anything the front end lists or searches, and get it audited before mainnet. A focused dApp typically takes 10 to 16 weeks with an experienced team; most of that time goes into the parts around the contract, not the contract itself. This guide walks through each step with a small but real example: a milestone escrow where a client locks payment and releases it when work is delivered.

```diagram
title: What runs where in a typical dApp
zone 2,0 3,0 "On-chain"
node user at 0,1 user "User" "Wallet in the browser"
node fe at 1,1 default "Front end" "Simulate, then sign"
node escrow at 2,0 chain "Escrow contract" "Funds and rules"
node token at 3,0 chain "ERC-20 token" "Moved with SafeERC20"
node indexer at 2,2 default "Indexer" "Reads contract events"
node db at 3,2 store "Database" "Deals, history, search"
edge user -> fe
edge fe -> escrow "fund / release"
edge escrow -> token "transfer"
edge escrow -> indexer "Funded, Released"
edge indexer -> db
edge db -> fe "lists and history" dashed
edge escrow -> fe "state reads" dashed up
```

## Step 1: Decide what goes on-chain

Everything on-chain is public, permanent and costs gas to write. Put there only what needs to be trustless: who owns what, and the rules for moving it. Everything else is cheaper and faster off-chain.

| Concern | On-chain | Off-chain |
|---|---|---|
| Funds and ownership | Yes | No |
| Rules for moving funds | Yes | No |
| Descriptions, files, images | Store a hash, not the content | Your database or IPFS |
| Search, lists, history views | No | An indexer reading contract events |
| User profiles, notifications | No | A normal backend |

For the escrow: the deal, the locked funds and the release or refund rules are on-chain. The job description and chat between client and provider are not.

## Step 2: Set up the contract project

[Foundry](https://getfoundry.sh/) is the fastest way to write and test Solidity today. Tests are written in Solidity too, so there is no context switching.

```bash
curl -L https://foundry.paradigm.xyz | bash && foundryup
forge init escrow && cd escrow
forge install OpenZeppelin/openzeppelin-contracts
echo "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/" > remappings.txt
```

[OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts/5.x/) gives you audited building blocks. Version 5 moved `ReentrancyGuard` to `utils/`, which trips up a lot of older tutorials.

## Step 3: Write the contract

Keep the contract small. Every line is something an auditor has to read and an attacker can probe.

```solidity
// src/MilestoneEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// Illustrative example for this guide. Not audited.
contract MilestoneEscrow is ReentrancyGuard {
    using SafeERC20 for IERC20;

    enum Status {
        None,
        Funded,
        Released,
        Refunded
    }

    struct Deal {
        address client;
        address provider;
        IERC20 token;
        uint256 amount;
        uint64 deadline;
        Status status;
    }

    mapping(uint256 => Deal) public deals;
    uint256 public nextId;

    event Funded(
        uint256 indexed id,
        address indexed client,
        address indexed provider,
        uint256 amount,
        uint64 deadline
    );
    event Released(uint256 indexed id);
    event Refunded(uint256 indexed id);

    error InvalidDeal();
    error NotClient();
    error WrongStatus();
    error TooEarly();

    function fund(
        address provider,
        IERC20 token,
        uint256 amount,
        uint64 deadline
    ) external nonReentrant returns (uint256 id) {
        if (provider == address(0) || amount == 0 || deadline <= block.timestamp)
            revert InvalidDeal();
        id = nextId++;
        deals[id] = Deal(msg.sender, provider, token, amount, deadline, Status.Funded);
        token.safeTransferFrom(msg.sender, address(this), amount);
        emit Funded(id, msg.sender, provider, amount, deadline);
    }

    /// The client approves the work and pays the provider.
    function release(uint256 id) external nonReentrant {
        Deal storage d = deals[id];
        if (msg.sender != d.client) revert NotClient();
        if (d.status != Status.Funded) revert WrongStatus();
        d.status = Status.Released; // update state before the external call
        d.token.safeTransfer(d.provider, d.amount);
        emit Released(id);
    }

    /// After the deadline, an unreleased deal can be refunded to the client.
    function refund(uint256 id) external nonReentrant {
        Deal storage d = deals[id];
        if (msg.sender != d.client) revert NotClient();
        if (d.status != Status.Funded) revert WrongStatus();
        if (block.timestamp < d.deadline) revert TooEarly();
        d.status = Status.Refunded;
        d.token.safeTransfer(d.client, d.amount);
        emit Refunded(id);
    }
}
```

Patterns worth copying even into much larger contracts:

- **Checks, effects, interactions.** Validate, update state, then call other contracts. Combined with `nonReentrant`, this closes the classic reentrancy hole.
- **`SafeERC20`.** Some tokens do not return `true` from `transfer`. The wrapper handles them.
- **Custom errors.** Cheaper than revert strings and easy to assert on in tests.

A real product needs more: a dispute path, tokens that charge fees on transfer (the contract would receive less than `amount`), and a decision about whether the contract is upgradeable. Write those decisions down before you write the code.

## Step 4: Test it properly

Test the happy path, every revert, and the boundaries in time. Fuzz tests try thousands of random inputs for you.

```solidity
// test/MilestoneEscrow.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Test} from "forge-std/Test.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {MilestoneEscrow} from "../src/MilestoneEscrow.sol";

contract MockToken is ERC20 {
    constructor() ERC20("Mock", "MOCK") {
        _mint(msg.sender, 1_000_000e18);
    }
}

contract MilestoneEscrowTest is Test {
    MilestoneEscrow escrow;
    MockToken token;
    address provider = makeAddr("provider");

    function setUp() public {
        escrow = new MilestoneEscrow();
        token = new MockToken();
        token.approve(address(escrow), type(uint256).max);
    }

    function _fund(uint256 amount) internal returns (uint256) {
        return escrow.fund(provider, token, amount, uint64(block.timestamp + 7 days));
    }

    function test_ReleasePaysProvider() public {
        uint256 id = _fund(100e18);
        escrow.release(id);
        assertEq(token.balanceOf(provider), 100e18);
    }

    function test_OnlyClientCanRelease() public {
        uint256 id = _fund(100e18);
        vm.prank(provider);
        vm.expectRevert(MilestoneEscrow.NotClient.selector);
        escrow.release(id);
    }

    function test_RefundBeforeDeadlineReverts() public {
        uint256 id = _fund(100e18);
        vm.expectRevert(MilestoneEscrow.TooEarly.selector);
        escrow.refund(id);
    }

    function test_RefundAfterDeadline() public {
        uint256 id = _fund(100e18);
        uint256 before = token.balanceOf(address(this));
        vm.warp(block.timestamp + 7 days);
        escrow.refund(id);
        assertEq(token.balanceOf(address(this)), before + 100e18);
    }

    function test_CannotReleaseTwice() public {
        uint256 id = _fund(100e18);
        escrow.release(id);
        vm.expectRevert(MilestoneEscrow.WrongStatus.selector);
        escrow.release(id);
    }

    function testFuzz_FundHoldsExactAmount(uint96 amount) public {
        vm.assume(amount > 0);
        _fund(amount);
        assertEq(token.balanceOf(address(escrow)), amount);
    }
}
```

```bash
forge test -vv
forge coverage   # aim for every branch, not a percentage
```

## Step 5: Deploy to a testnet

Use a deployment script so deployments are repeatable, and keep the deployer key in Foundry's encrypted keystore rather than in an environment variable.

```solidity
// script/Deploy.s.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Script} from "forge-std/Script.sol";
import {MilestoneEscrow} from "../src/MilestoneEscrow.sol";

contract Deploy is Script {
    function run() external returns (MilestoneEscrow escrow) {
        vm.startBroadcast();
        escrow = new MilestoneEscrow();
        vm.stopBroadcast();
    }
}
```

```bash
cast wallet import deployer --interactive   # paste a testnet-only key once
forge script script/Deploy.s.sol --rpc-url "$SEPOLIA_RPC_URL" --account deployer --broadcast
```

Verify the source on the block explorer (add `--verify` with an explorer API key) so users can read what they are interacting with.

## Step 6: Build the front end

[viem](https://viem.sh/) is a small, well-typed TypeScript library for talking to EVM chains. Copy the ABI from `out/MilestoneEscrow.sol/MilestoneEscrow.json` and declare it `as const` so viem can type every call.

```ts
// escrow.ts
import {
  createPublicClient,
  createWalletClient,
  custom,
  http,
  parseEventLogs,
  parseUnits,
  erc20Abi,
} from "viem";
import { sepolia } from "viem/chains";
import { escrowAbi } from "./escrowAbi"; // the ABI array, exported `as const`

const ESCROW = "0xYourDeployedEscrow" as const;
const publicClient = createPublicClient({ chain: sepolia, transport: http() });
const walletClient = createWalletClient({
  chain: sepolia,
  transport: custom(window.ethereum!),
});

export async function fundDeal(
  token: `0x${string}`,
  provider: `0x${string}`,
  amount: string,
  days: number,
) {
  const [account] = await walletClient.requestAddresses();
  const value = parseUnits(amount, 18); // use the token's real decimals
  const deadline = BigInt(Math.floor(Date.now() / 1000) + days * 86400);

  // 1. Allow the escrow to pull the tokens
  const approveHash = await walletClient.writeContract({
    account,
    address: token,
    abi: erc20Abi,
    functionName: "approve",
    args: [ESCROW, value],
  });
  await publicClient.waitForTransactionReceipt({ hash: approveHash });

  // 2. Fund the deal
  const hash = await walletClient.writeContract({
    account,
    address: ESCROW,
    abi: escrowAbi,
    functionName: "fund",
    args: [provider, token, value, deadline],
  });
  const receipt = await publicClient.waitForTransactionReceipt({ hash });

  // 3. Read the deal ID from the emitted event, not from a guess
  const [funded] = parseEventLogs({
    abi: escrowAbi,
    logs: receipt.logs,
    eventName: "Funded",
  });
  return funded.args.id;
}

export async function getDeal(id: bigint) {
  return publicClient.readContract({
    address: ESCROW,
    abi: escrowAbi,
    functionName: "deals",
    args: [id],
  });
}
```

Most users will reach your dApp through a wallet connector library that wraps this with a "Connect wallet" button and support for many wallets. The calls underneath are the same.

A few front-end details matter more than they seem:

- Show every transaction's status: waiting for signature, pending, confirmed, failed.
- Simulate before asking for a signature (`publicClient.simulateContract`) so users see "this will fail" before paying gas.
- Never trust amounts typed into the UI. Re-read balances and allowances from the chain.

## Step 7: Index events for lists and history

Reading `deals(id)` one at a time works for a detail page. For "all my deals" or a searchable list, read the contract's events into a database with an indexer, either a hosted subgraph or a small service that polls `getLogs` and stores the results. This is why the escrow emits an event for every state change.

## Step 8: Audit, launch and operate

Before mainnet:

1. **Freeze the scope** and write a short specification of what the contract must and must not allow.
2. **Get an external audit.** Fix findings, then have the fixes reviewed.
3. **Use a multisig** for any admin role, and decide in advance what you will do if a bug is found.
4. **Launch with limits**, for example a cap on deal size, and raise them as confidence grows.
5. **Monitor events** and alert on anything unusual, such as many refunds in a short period.

## Timeline and cost

These are the ranges we see for a focused dApp with one to three contracts, a web front end and an indexer:

| Phase | Typical duration |
|---|---|
| Discovery and specification | 1-2 weeks |
| Design and prototyping | 2-3 weeks |
| Contracts, front end and backend | 4-8 weeks |
| Testing and security review | 1-2 weeks, plus the external audit's own lead time |
| Deployment and launch | 1 week |

Overall that is roughly 10 to 16 weeks, with budgets typically between $40,000 and $120,000 depending on scope. The biggest cost drivers are the number of contracts and how much value they hold, which drives audit depth, plus integrations with other protocols and the size of the front end. An external audit is usually priced separately.

## What we would do

Write the specification before the contract, keep the on-chain part as small as possible, and spend real effort on tests and on the front end's transaction states. Most dApps that fail do so because users cannot understand what is happening, not because of the contract.

If you are planning one, our [dApp development](/services/dapp-development) page lists what we deliver in each phase.

---

OnChain · 15 Bld. Iuliu Maniu, 061075 Bucharest, Romania · contact@onchain.ro · https://www.onchain.ro
