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

# Advanced Build

> Build Voltaire from source for maximum performance, custom targets, and supply chain security

Voltaire is a Zig library at its core. The TypeScript and native bindings you install from npm are pre-built artifacts optimized for bundle size (`ReleaseSmall`). Building from source unlocks capabilities not available in the distributed packages.

## Why Build From Source

### Performance Optimization

npm distributions use `ReleaseSmall` which prioritizes bundle size over raw speed. Building from source with `ReleaseFast` yields measurable performance gains:

```bash theme={null}
# Default npm build (size-optimized)
zig build build-ts-wasm           # ReleaseSmall - ~180KB WASM

# Performance build (speed-optimized)
zig build build-ts-wasm-fast      # ReleaseFast - ~240KB WASM, faster execution
```

For native FFI, the difference is even more significant since native code benefits from aggressive LLVM optimizations:

```bash theme={null}
zig build build-ts-native         # ReleaseFast by default
```

### Granular Tree-Shaking

The full Voltaire WASM bundle includes all primitives and crypto. If you only need specific functionality, build individual WASM modules:

```bash theme={null}
# Build only what you need
zig build keccak256-wasm          # ~8KB  - just Keccak-256
zig build blake2-wasm             # ~12KB - just BLAKE2b
zig build address-wasm            # ~15KB - address operations

# Build all individual modules
zig build crypto-wasm
```

This produces `wasm/crypto/*.wasm` files you can load independently:

```typescript theme={null}
// Load only keccak256 (~8KB instead of ~180KB)
const keccak = await WebAssembly.instantiateStreaming(
  fetch('/wasm/crypto/keccak256.wasm')
);
```

### Custom Platform Targets

Zig's cross-compilation is [best-in-class](https://zig.guide/0.11/build-system/cross-compilation/). Build for any platform supporting C FFI:

```bash theme={null}
# Cross-compile for specific platforms
zig build -Dtarget=aarch64-linux          # ARM64 Linux (Raspberry Pi, AWS Graviton)
zig build -Dtarget=x86_64-windows         # Windows x64
zig build -Dtarget=riscv64-linux          # RISC-V Linux
zig build -Dtarget=mips-linux-gnueabi     # MIPS embedded

# Build all supported native platforms
zig build build-native-all
```

Pre-built distributions only ship macOS (arm64/x64), Linux (arm64/x64), and Windows (x64). Building from source lets you target:

* Embedded systems (ARM Cortex, RISC-V, MIPS)
* Exotic operating systems (FreeBSD, NetBSD, Haiku)
* Custom architectures with C FFI support
* WebAssembly variants (wasm32-freestanding vs wasm32-wasi)

### Vendored Dependencies

Building from source means you control every byte of code that executes:

```bash theme={null}
git clone https://github.com/voltaire-org/voltaire.git
cd voltaire
git submodule update --init --recursive   # Fetch all vendored deps
zig build                                  # Build everything from source
```

**Benefits:**

* **Audit everything** - No opaque binaries, every line is reviewable
* **Contribute upstream** - Make changes and submit PRs easily
* **LLM context** - Full codebase available for AI-assisted development
* **Reproducible builds** - Same source always produces same output

## Supply Chain Security

<Warning>
  The npm ecosystem has demonstrated systemic vulnerability to supply chain attacks that specifically target cryptocurrency applications.
</Warning>

### Recent Attacks

**September 2025**: A [phishing attack compromised 18 npm packages](https://www.trendmicro.com/en_us/research/25/i/npm-supply-chain-attack.html) with 2+ billion weekly downloads (chalk, debug, ansi-styles). Malicious code injected wallet-draining malware that hooked `window.ethereum` and Solana APIs.

**December 2024**: The [@solana/web3.js library was backdoored](https://thehackernews.com/2024/12/researchers-uncover-backdoor-in-solanas.html) (CVE-2024-54134) through spear-phishing, stealing private keys from developers.

These attacks share a pattern:

1. Compromise trusted maintainer accounts
2. Inject malicious code into popular packages
3. Target cryptocurrency wallets specifically
4. Exist for hours before detection

### Defense Through Source Builds

Building from source with vendored dependencies eliminates npm as an attack vector:

```bash theme={null}
# Clone with all submodules pinned to specific commits
git clone --recurse-submodules https://github.com/voltaire-org/voltaire.git

# Verify git history and commit signatures
git log --show-signature

# Build entirely from source - no npm fetch during build
zig build
```

**What this eliminates:**

* npm registry as single point of failure
* Account compromise attacks (no accounts to compromise)
* Malicious version injection (you control the commits)
* Typosquatting attacks (no package names to confuse)

**We encourage anyone handling significant value to build from source.** The cryptocurrency industry faces unique risk from supply chain attacks, and source builds are the only complete mitigation.

## Build Prerequisites

```bash theme={null}
# Required
zig version          # 0.15.x (https://ziglang.org/download/)
cargo --version      # Rust 1.70+ (for crypto wrappers)

# Optional
bun --version        # For TypeScript tests/builds
go version           # For Go bindings
```

### Quick Start

```bash theme={null}
# Clone repository
git clone --recurse-submodules https://github.com/voltaire-org/voltaire.git
cd voltaire

# Install dependencies and build
zig build deps       # Fetch all dependencies
zig build           # Full build (Zig + C + Rust libraries)

# Run tests
zig build test      # All Zig tests
```

## Build Commands Reference

### Core Builds

| Command                             | Description       | Use Case               |
| ----------------------------------- | ----------------- | ---------------------- |
| `zig build`                         | Full build        | Development            |
| `zig build -Doptimize=ReleaseFast`  | Performance build | Benchmarking           |
| `zig build -Doptimize=ReleaseSmall` | Size-optimized    | Distribution           |
| `zig build -Doptimize=ReleaseSafe`  | Safe release      | Production with checks |

### TypeScript/WASM Builds

| Command                        | Description               | Output                             |
| ------------------------------ | ------------------------- | ---------------------------------- |
| `zig build build-ts-wasm`      | WASM (ReleaseSmall)       | `wasm/primitives.wasm`             |
| `zig build build-ts-wasm-fast` | WASM (ReleaseFast)        | `wasm/primitives-fast.wasm`        |
| `zig build build-ts-native`    | Native FFI                | `native/libprimitives_ts_native.*` |
| `zig build crypto-wasm`        | Individual crypto modules | `wasm/crypto/*.wasm`               |

### Cross-Platform Builds

| Command                               | Description             |
| ------------------------------------- | ----------------------- |
| `zig build build-native-all`          | All supported platforms |
| `zig build build-native-darwin-arm64` | macOS Apple Silicon     |
| `zig build build-native-linux-x64`    | Linux x64               |
| `zig build build-native-win32-x64`    | Windows x64             |

### Testing

| Command                               | Description           |
| ------------------------------------- | --------------------- |
| `zig build test`                      | All Zig tests         |
| `zig build test -Dtest-filter=keccak` | Filter tests          |
| `zig build test-ts`                   | TypeScript tests      |
| `zig build test-all`                  | Zig + TypeScript + Go |

## WASM Build Modes

Zig supports two primary [WASM targets](https://wazero.io/languages/zig/):

### wasm32-wasi (Default)

Used when C libraries are involved (blst, c-kzg, Rust crypto):

```zig theme={null}
const wasm_target = b.resolveTargetQuery(.{
    .cpu_arch = .wasm32,
    .os_tag = .wasi,
});
```

* Requires WASI runtime (browser polyfills available)
* Full libc support
* All crypto features enabled

### wasm32-freestanding

For pure Zig code without C dependencies:

```zig theme={null}
const wasm_target = b.resolveTargetQuery(.{
    .cpu_arch = .wasm32,
    .os_tag = .freestanding,
});
```

* No WASI requirements
* Smaller output
* Limited to pure Zig implementations

## Optimization Modes

| Mode           | Size     | Speed   | Safety         | Use Case     |
| -------------- | -------- | ------- | -------------- | ------------ |
| `Debug`        | Large    | Slow    | Full           | Development  |
| `ReleaseSafe`  | Medium   | Fast    | Bounds checked | Production   |
| `ReleaseFast`  | Medium   | Fastest | Minimal        | Benchmarking |
| `ReleaseSmall` | Smallest | Good    | Minimal        | Distribution |

`ReleaseSmall` is 20-40% smaller than `ReleaseFast` but can be 10-30% slower for compute-intensive operations like cryptographic primitives.

## External Resources

* [Zig 0.15.1 Release Notes](https://ziglang.org/download/0.15.1/release-notes.html) - Language reference
* [Zig Build System Guide](https://rdunnington.github.io/blog/2025-07-17/page) - Intermediate build system usage
* [WebAssembly with Zig](https://dev.to/sleibrock/webassembly-with-zig-part-1-4onm) - WASM tutorial
* [Zig Cross-Compilation](https://zig.guide/0.11/build-system/cross-compilation/) - Target triples and flags
* [WASM Target Reference](https://wazero.io/languages/zig/) - wasm32-wasi vs freestanding

## Learn More

<CardGroup cols={2}>
  <Card title="Getting Started" icon="rocket" href="/getting-started">
    Standard installation via npm/bun
  </Card>

  <Card title="Branded Types" icon="tag" href="/concepts/branded-types">
    Type-safe primitives with zero overhead
  </Card>
</CardGroup>
