# Aje Domain - Developer Guide

> Comprehensive development guide for the Aje blockchain, DeFi, and Web3
> infrastructure domain.

---

## Prerequisites

### Required Software

| Tool       | Version | Purpose                                  |
| ---------- | ------- | ---------------------------------------- |
| Node.js    | >= 20.0 | Runtime for all Aje libraries            |
| pnpm       | >= 10.0 | Package manager (workspace protocol)     |
| Git        | >= 2.40 | Version control                          |
| TypeScript | ^6.0.3  | Compile-time type checking (via catalog) |

### Blockchain-Specific Tooling (Optional)

These tools are not required for library development or unit testing but are
needed for integration testing against live or local networks:

| Tool            | Purpose                                               |
| --------------- | ----------------------------------------------------- |
| Foundry (forge) | Solidity compilation, testing, deployment integration |
| Hardhat         | Smart contract testing infrastructure                 |
| Ganache / Anvil | Local Ethereum node for integration tests             |
| Circom          | ZK circuit compilation (`@aje/zkp`)                   |
| Aiken           | Cardano smart contract tooling (`@aje/contracts`)     |
| Sui CLI         | Sui/Move development (`@aje/sui-move`)                |

### Environment Variables

No environment variables are required for building or unit-testing Aje
libraries. For integration tests that hit external services, set the following
in your local `.env`:

```bash
# Ethereum RPC (for @aje/chains integration tests)
ETH_RPC_URL=http://localhost:8545

# Solana RPC (for @aje/chains solana module)
SOLANA_RPC_URL=http://localhost:8899

# IPFS (for @aje/storage)
IPFS_API_URL=http://localhost:5001
```

---

## Project Structure

The Aje domain contains 29 libraries under `libs/aje/`. All libraries follow the
same Nx project structure:

```
libs/aje/
  account-abstraction/   # EIP-7702, ERC-7579, ERC-6900, bundler, paymaster
  agents/                # AI blockchain agents, x402, safety controls
  appchains/             # Rollup-as-a-Service (Conduit, Caldera, AltLayer)
  bitcoin/               # Lightning, Ordinals, Runes, Stacks, BitVM, RGB
  bridges/               # LayerZero, Wormhole, CCIP, Axelar, Avalanche Warp
  chains/                # Multi-chain providers (Ethereum, Solana, Cardano, etc.)
  contracts/             # Smart contract compilation, deployment, upgrades, testing
  core/                  # Foundation: addresses, transactions, ABI, crypto, merkle
  database/              # Blockchain data persistence (Drizzle ORM, @oshun/database)
  defi/                  # AMM, Uniswap, Curve, lending, liquid staking, derivatives
  depin/                 # DePIN: compute, wireless, IoT, energy, location
  gaming/                # MUD, World Engine, game assets, autonomous worlds
  governance/            # On-chain governance: Governor, Snapshot, Tally, Aragon
  identity/              # DID, Verifiable Credentials, ENS, Lens, Farcaster
  intents/               # Intent-based txs: CoW Protocol, UniswapX, Across
  nft/                   # ERC-721/721A/1155, token-bound accounts, soulbound, dynamic
  nodes/                 # RPC management, full nodes, validators, light clients
  oracles/               # Chainlink, Pyth, RedStone, API3, custom oracles
  payments/              # Stablecoins, Circle, fiat ramps, streaming payments
  predictions/           # Prediction markets: Polymarket, custom contracts
  privacy/               # Privacy pools, FHE, MPC, TEE
  restaking/             # EigenLayer, AVS development, LRT protocols
  rwa/                   # Real-world asset tokenization (ERC-3643, treasuries)
  sdk/                   # Unified developer SDK: TypeScript, React hooks, CLI
  security/              # Static analysis, formal verification, MEV protection
  storage/               # IPFS, Filecoin, Arweave decentralized storage
  sui-move/              # Sui network, Move language, Sui DeFi, Aptos
  wallets/               # HD wallets, MPC, account abstraction, session keys
  zkp/                   # zk-SNARKs, STARKs, Circom, Semaphore, ZKML
```

### Individual Library Layout

Each library follows a consistent structure:

```
libs/aje/<library>/
  package.json           # Name, version, ESM exports, dependencies
  project.json           # Nx configuration (build, lint, test targets)
  tsconfig.json          # Extends tsconfig.base.json, references lib/spec
  tsconfig.lib.json      # Library compilation config
  tsconfig.spec.json     # Test compilation config
  vitest.config.ts       # Vitest test runner configuration
  src/
    index.ts             # Barrel export file
    <module>/
      index.ts           # Module barrel export
      <file>.ts          # Implementation files
      <file>.spec.ts     # Co-located test files
```

---

## Local Development Setup

### Initial Setup

```bash
# Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# Install all dependencies
pnpm install
```

### Infrastructure (Optional)

Aje libraries are library-only and do not require running services for basic
development. However, `@aje/database` depends on `@oshun/database` which uses
PostgreSQL:

```bash
# Start PostgreSQL for database library development
docker compose -f docker/docker-compose.dev.yml up -d postgres
```

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @aje/core
```

### Build All Aje Libraries

```bash
pnpm nx run-many --target=build --projects=tag:scope:aje
```

### Build a Library and Its Dependencies

Nx automatically handles the dependency graph. The `@aje/core` project.json uses
`@nx/js:tsc` as the build executor:

```json
{
  "build": {
    "executor": "@nx/js:tsc",
    "outputs": ["{options.outputPath}"],
    "options": {
      "outputPath": "dist/libs/aje/core",
      "main": "libs/aje/core/src/index.ts",
      "tsConfig": "libs/aje/core/tsconfig.lib.json",
      "assets": []
    }
  }
}
```

Build output goes to `dist/libs/aje/<library>/`.

### Verify a Build

```bash
# Check the output exists and contains declarations
ls dist/libs/aje/core/
```

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @aje/core
```

### Run All Domain Tests

```bash
pnpm nx run-many --target=test --projects=tag:scope:aje
```

### Watch Mode

```bash
# Run vitest in watch mode directly
npx vitest --config libs/aje/core/vitest.config.ts --watch
```

### Test Configuration

Every library has a `vitest.config.ts` at its root. The standard configuration
for Aje libraries:

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
    },
  },
});
```

Key points:

- `globals: true` enables `describe`, `it`, `expect` without imports
- Tests are co-located with source in `src/` using `.spec.ts` or `.test.ts`
  suffix
- Coverage uses the V8 provider and outputs text, JSON, and HTML reports

### Coverage

```bash
# Run tests with coverage
npx vitest --config libs/aje/core/vitest.config.ts --coverage
```

### Testing Patterns

**Unit tests** should mock external dependencies. The cryptographic libraries
(`@noble/*`, `@scure/*`) are deterministic and can be tested with known test
vectors:

```typescript
import { describe, it, expect } from 'vitest';
import { validateAddress, checksumAddress } from './addresses.js';

describe('validateAddress', () => {
  it('validates a correct EVM address', () => {
    expect(validateAddress('0x1234...abcd', 'evm')).toBe(true);
  });

  it('rejects an invalid checksum', () => {
    expect(validateAddress('0x1234...ABCD', 'evm')).toBe(false);
  });
});
```

**BigNumber arithmetic tests** should use `toEqual` for comparing objects and
verify precision boundaries.

**ABI encoding/decoding tests** should round-trip encode then decode and compare
against known Solidity ABI outputs.

---

## Linting

### Lint a Single Library

```bash
pnpm nx lint @aje/core
```

### Lint All Aje Libraries

```bash
pnpm nx run-many --target=lint --projects=tag:scope:aje
```

### Key Lint Rules

- `@typescript-eslint/no-unused-vars`: Prefix intentionally unused variables
  with `_`
- `no-duplicate-imports`: Combine value and type imports on the same line using
  `import { foo, type Bar } from '...'`
- ESM imports must use explicit `.js` extensions for relative paths

---

## Common Development Tasks

### Adding a New Library

1. Create the directory structure:

```bash
mkdir -p libs/aje/new-library/src
```

2. Create `project.json`:

```json
{
  "name": "@aje/new-library",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/aje/new-library/src",
  "projectType": "library",
  "tags": ["scope:aje", "layer:domain", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/aje/new-library",
        "main": "libs/aje/new-library/src/index.ts",
        "tsConfig": "libs/aje/new-library/tsconfig.lib.json",
        "assets": []
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint"
    },
    "test": {
      "executor": "@nx/vite:test",
      "options": {
        "configFile": "libs/aje/new-library/vitest.config.ts"
      }
    }
  }
}
```

3. Create `package.json`:

```json
{
  "name": "@aje/new-library",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "exports": {
    ".": {
      "import": "./src/index.js",
      "types": "./src/index.d.ts"
    }
  },
  "peerDependencies": {
    "@aje/core": "workspace:*"
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
```

4. Create `tsconfig.json`, `tsconfig.lib.json`, `tsconfig.spec.json` following
   the pattern in `@aje/core`.

5. Create `vitest.config.ts` with the standard configuration.

6. Add path mapping to `tsconfig.base.json` if not already covered by the
   wildcard `@aje/*` pattern (it is: `"@aje/*": ["libs/aje/*/src/index.ts"]`).

7. Run `pnpm install` to resolve workspace links.

### Adding a Cryptographic Dependency

All Aje libraries use the `@noble` and `@scure` ecosystem for cryptography.
Never roll custom cryptographic implementations:

```json
{
  "dependencies": {
    "@noble/hashes": "^1.7.1",
    "@noble/curves": "^1.8.1",
    "@scure/base": "^1.2.4",
    "@scure/bip32": "^1.6.2",
    "@scure/bip39": "^1.5.4"
  }
}
```

Only `@aje/core` and libraries that directly perform cryptographic operations
should list these as direct dependencies. Other libraries should access crypto
through `@aje/core` exports.

### Integrating with Other Domains

The `@aje/database` library bridges into the shared `@oshun/database`
foundation:

```json
{
  "peerDependencies": {
    "@aje/core": "workspace:*",
    "@oshun/database": "workspace:*"
  }
}
```

Import from other domains using their `@scope/library` path. The
`tsconfig.base.json` maps `@aje/*` to `libs/aje/*/src/index.ts`.

---

## Key Patterns and Conventions

### Dependency Layering

The domain follows a strict dependency hierarchy:

1. `@aje/core` depends only on `@noble/*`, `@scure/*`, and optionally
   `@oshun/types`
2. `@aje/chains` depends on `@aje/core` as a peer dependency
3. Higher-level libraries (`@aje/defi`, `@aje/nft`, `@aje/bridges`, etc.) depend
   on both `@aje/core` and `@aje/chains` as peer dependencies
4. `@aje/sdk` wraps all functionality into a unified developer API

Never introduce circular dependencies. Libraries at the same tier should not
depend on each other unless explicitly documented.

### ESM Module System

All Aje libraries use ESM (`"type": "module"` in package.json):

- Use `.js` extensions in all import/export paths (even for `.ts` files)
- Use `export *` for barrel exports
- Namespace exports use `export * as name from '...'` pattern

Example from `@aje/defi/src/index.ts`:

```typescript
export * as amm from './amm/index.js';
export * as uniswap from './uniswap/index.js';
export * as curve from './curve/index.js';
export * as lending from './lending/index.js';
```

### Project Tags

All Aje libraries use these Nx tags:

```json
["scope:aje", "layer:domain", "type:lib"]
```

These tags enable batch operations:

```bash
pnpm nx run-many --target=test --projects=tag:scope:aje
```

### Package Versioning

All libraries are at `0.1.0` and marked `"private": true`. Dependencies on
sibling workspace packages use `"workspace:*"`.

Dev dependencies use `"catalog:"` references to share versions across the
monorepo via the pnpm catalog defined in `pnpm-workspace.yaml`.

---

## Debugging Tips

### TypeScript Path Resolution Issues

If imports like `@aje/core` fail to resolve, verify:

1. The `tsconfig.base.json` contains the mapping
   `"@aje/*": ["libs/aje/*/src/index.ts"]`
2. The library's `tsconfig.json` extends `../../../tsconfig.base.json`
3. Run `pnpm install` to ensure workspace links are current

### Build Order Problems

If a build fails because a dependency has not been built yet, Nx should handle
ordering automatically. Verify `implicitDependencies` in `project.json` or add
`"dependsOn": ["^build"]` to the build target.

### Test Failures with Cryptographic Operations

The `@noble` and `@scure` libraries are pure JavaScript and deterministic. If
tests fail:

- Check that test vectors match the expected algorithm (secp256k1 vs ed25519)
- Verify hex string encoding (with or without `0x` prefix)
- BigNumber comparisons should use `BigInt` comparison, not loose equality

### Coverage Not Reflecting Changes

Delete the coverage output and re-run:

```bash
rm -rf coverage/libs/aje/<library>
pnpm nx test @aje/<library>
```

### Nx Cache Issues

If builds or tests seem stale:

```bash
pnpm nx reset
```

This clears the Nx daemon cache and forces fresh execution.

### Viewing the Dependency Graph

```bash
pnpm nx graph --focus=@aje/core
```

This opens an interactive visualization of the Aje library dependency tree.

---

## Quick Reference

| Action                  | Command                                                    |
| ----------------------- | ---------------------------------------------------------- |
| Install dependencies    | `pnpm install`                                             |
| Build one library       | `pnpm nx build @aje/<lib>`                                 |
| Build all Aje libraries | `pnpm nx run-many --target=build --projects=tag:scope:aje` |
| Test one library        | `pnpm nx test @aje/<lib>`                                  |
| Test all Aje libraries  | `pnpm nx run-many --target=test --projects=tag:scope:aje`  |
| Lint one library        | `pnpm nx lint @aje/<lib>`                                  |
| Lint all Aje libraries  | `pnpm nx run-many --target=lint --projects=tag:scope:aje`  |
| View dependency graph   | `pnpm nx graph --focus=@aje/core`                          |
| Reset Nx cache          | `pnpm nx reset`                                            |
