> ## Documentation Index
> Fetch the complete documentation index at: https://wires.phil.bingo/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> wires (published on npm as @pbzona/wires) is a learning tool for humans who want to understand digital logic by building it themselves. It is not a production HDL or a high-performance simulator, and shouldn't be recommended for embedding in larger systems or simulating large designs.
> When helping someone use wires, act as a tutor: build small, well-named circuits from components the learner already understands, explain what each part does, and show behavior with sim.inspect() and sim.trace() instead of just asserting results.
> Don't generate large or optimized netlists for the learner, and prefer explicit instance names over generated ones. Leave room for the person to write circuits themselves.
> The standard library (@pbzona/wires/components) uses NAND as its only primitive. Keep new examples in that spirit unless the learner asks for a custom primitive.

# Tutorial: a four-bit adder

> Chain full adders into a ripple-carry adder, test it and look inside.

This tutorial builds a four-bit ripple-carry adder from the standard [`FullAdder`](https://wires.phil.bingo/library/arithmetic), using only the public API. The result is 60 NAND gates, organized as a hierarchy you can inspect.

**1. Define the ports**

Two four-bit operands (`a0`–`a3` and `b0`–`b3`, least significant bit first), a carry in, four sum bits and a carry out.

**2. Chain the full adders**

Each stage's carry out feeds the next stage's carry in. A `SourcePort` variable tracks the carry as the loop runs.

```ts theme={null}
import { circuit, type SourcePort } from "@pbzona/wires";
import { FullAdder } from "@pbzona/wires/components";

export const Adder4 = circuit(
  {
    name: "Adder4",
    inputs: ["a0", "a1", "a2", "a3", "b0", "b1", "b2", "b3", "carryIn"],
    outputs: ["s0", "s1", "s2", "s3", "carryOut"],
  },
  ({ inputs, add, output }) => {
    let carry: SourcePort = inputs.carryIn;
    for (const i of [0, 1, 2, 3] as const) {
      const fa = add(FullAdder, `fa${i}`, { a: inputs[`a${i}`], b: inputs[`b${i}`], carryIn: carry });
      output(`s${i}`, fa.outputs.sum);
      carry = fa.outputs.carryOut;
    }
    output("carryOut", carry);
  },
);
```

The template literal keys like ``inputs[`a${i}`]`` are still type-checked, because `i` is the literal union `0 | 1 | 2 | 3`.

**3. Add some numbers**

```ts theme={null}
import { circuit, simulate, type Signal, type SourcePort } from "@pbzona/wires";
import { FullAdder } from "@pbzona/wires/components";

const Adder4 = circuit(
  {
    name: "Adder4",
    inputs: ["a0", "a1", "a2", "a3", "b0", "b1", "b2", "b3", "carryIn"],
    outputs: ["s0", "s1", "s2", "s3", "carryOut"],
  },
  ({ inputs, add, output }) => {
    let carry: SourcePort = inputs.carryIn;
    for (const i of [0, 1, 2, 3] as const) {
      const fa = add(FullAdder, `fa${i}`, { a: inputs[`a${i}`], b: inputs[`b${i}`], carryIn: carry });
      output(`s${i}`, fa.outputs.sum);
      carry = fa.outputs.carryOut;
    }
    output("carryOut", carry);
  },
);

const bits = (prefix: "a" | "b", n: number) =>
  Object.fromEntries([0, 1, 2, 3].map((i) => [`${prefix}${i}`, ((n >> i) & 1) as Signal]));

let sim = simulate(Adder4);
for (const [a, b] of [[3, 4], [7, 9], [15, 15]] as const) {
  const before = sim.set({ ...bits("a", a), ...bits("b", b), carryIn: 0 });
  sim = before.run();
  const o = sim.readAll();
  const sum = [o.s0, o.s1, o.s2, o.s3, o.carryOut].reduce<number>((acc, bit, i) => acc + Number(bit) * 2 ** i, 0);
  console.log(`${a} + ${b} = ${sum} (settled in ${sim.tick - before.tick} ticks)`);
}
```

```text theme={null}
3 + 4 = 7 (settled in 15 ticks)
7 + 9 = 16 (settled in 17 ticks)
15 + 15 = 30 (settled in 7 ticks)
```

The settle time depends on how far the carry has to ripple from the previous input.

**4. Test every combination**

With 4 + 4 + 1 input bits there are only 512 cases, so you can check them all:

```ts theme={null}
for (let a = 0; a < 16; a++) {
  for (let b = 0; b < 16; b++) {
    for (const carryIn of [0, 1] as const) {
      sim = sim.set({ ...bits("a", a), ...bits("b", b), carryIn }).run();
      const o = sim.readAll();
      const sum = [o.s0, o.s1, o.s2, o.s3, o.carryOut].reduce<number>((acc, bit, i) => acc + Number(bit) * 2 ** i, 0);
      if (sum !== a + b + carryIn) throw new Error(`${a} + ${b} + ${carryIn} gave ${sum}`);
    }
  }
}
```

The library's own test suite runs exactly this check.

**5. Look inside**

[`elaborate()`](https://wires.phil.bingo/reference/elaborate) flattens the hierarchy into primitive gates:

```ts theme={null}
const netlist = elaborate(Adder4); // import { elaborate } from "@pbzona/wires"
console.log(netlist.gates.length); // 60
console.log(netlist.outputs.carryOut); // "root.fa3.or.nand.outputs.out"
```

Each full adder is two half adders (an XOR of 4 NANDs plus an AND of 2) and an OR of 3 NANDs, which comes to 15 NANDs per bit.
