# Aje Domain — Architecture

> Architectural overview of the Aje blockchain and Web3 infrastructure domain:
> 31 libraries, layered dependency model, cryptographic philosophy, and
> integration contracts.

---

Aje is the blockchain and Web3 infrastructure domain of the Oshun monorepo. It
is named after the Yoruba orisha of commerce, wealth, and fair business — a
deity who ensures that trade is equitable and prosperity flows to those who work
honestly. In practical terms, Aje is a collection of 31 composable TypeScript
libraries that any other Oshun domain can import to gain blockchain
capabilities: wallet management, multi-chain network access, DeFi protocol
integration, NFT infrastructure, smart contract tooling, zero-knowledge proofs,
and much more.

The domain solves a fundamental platform problem: blockchain and Web3
capabilities are deeply specialised, change rapidly, and carry serious financial
and security consequences when implemented incorrectly. By concentrating all of
this knowledge in a single, well-tested library domain, every Oshun feature that
touches crypto — from cosmetic NFT ownership in the V2 game to Concordia
settlement escrows — can rely on audited, shared primitives rather than
re-implementing them from scratch in each consuming service.

Aje ships no applications or services of its own. It is a pure library domain:
its value is entirely in what it gives to others.

---

## Design Principles

1. **Library-only domain** — Aje contains no applications or services
   (`apps/aje` and `services/aje` do not exist). It is a pure library domain
   providing composable primitives to any other domain that needs blockchain
   capabilities.
2. **Layered dependencies** — A strict dependency hierarchy prevents circular
   imports. `@aje/core` sits at the foundation; higher-level libraries build on
   top without reaching sideways.
3. **Audited cryptography only** — All cryptographic operations use `@noble` and
   `@scure` libraries. No custom crypto implementations. This is a hard rule,
   not a preference.
4. **Chain abstraction** — `@aje/chains` provides a unified interface across all
   supported networks. Chain-specific code is encapsulated within named modules,
   not scattered across libraries.
5. **TypeScript throughout** — Aje is a pure TypeScript domain. No Rust, no
   WASM. The domain's performance requirements are met by delegating to
   well-optimized pure TypeScript crypto libraries.

---

## Library Dependency Graph

The graph below shows how the 31 Aje packages relate to one another. Dependency
relationships are taken from each package's `package.json`. `@aje/core` declares
`@oshun/types` as an **optional** peer; domain packages declare `@aje/core` as a
peer, and packages needing chain access additionally declare `@aje/chains` as a
peer. Most packages also depend on the workspace `@oshun/crypto` package and on
`@noble/*` / `@scure/*` directly.

```
@aje/sdk                       ← composition layer (core/react/python/cli/docs)
    │   peer: @aje/core, @aje/chains
    │
@aje/wallets, @aje/defi, @aje/nft, @aje/contracts, @aje/bridges,
@aje/account-abstraction, @aje/identity, @aje/governance, @aje/oracles,
@aje/rwa, @aje/zkp, @aje/agents, …
    │   peer: @aje/core  (+ @aje/chains where chain access is required)
    │
@aje/chains                    ← multi-chain provider layer
    │   peer: @aje/core
    │
@aje/core                      ← crypto primitives, addresses, ABI, types
        optional peer: @oshun/types ;  deps: @noble/*, @scure/*, @oshun/crypto

Standalone packages:
  @aje/rpc                     ← no dependencies, no peers (self-contained)
  @aje/settlement-escrow       ← deps: @concordia/contracts, zod (no @aje/core)
  @aje/database                ← peers: @aje/core, @oshun/database
```

---

## Library Organization (31 Libraries)

The 31 libraries are grouped into six layers. Each layer builds on the one below
it, and no package in a lower layer imports from a higher one.

### Foundation Layer

These four packages form the base that all other Aje libraries depend on. Every
higher-level package ultimately relies on `@aje/core` for its types and
cryptographic primitives.

| Library         | Purpose                                                                                                                                                 |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@aje/core`     | Crypto primitives, addresses (EVM/Solana/Cardano/Bitcoin), transactions, ABI/RLP encoding, Merkle trees, event parsing, BigNumber, errors               |
| `@aje/chains`   | Multi-chain provider layer: Ethereum, Arbitrum, Optimism, zkSync, Polygon, Avalanche, Cardano, Solana; chain abstraction interface                      |
| `@aje/rpc`      | `OshunRpcClient` — self-contained multi-chain JSON-RPC client with retry, fallback, fan-out, rate limiting; Ethereum/Bitcoin/Avalanche/Solana providers |
| `@aje/database` | PostgreSQL DDL and parameterized query builders (via `@oshun/database`) for chain/wallet/DeFi data; block indexer; Prisma/Drizzle schema generator      |

### Wallet and Account Layer

These two packages handle everything related to key custody and smart account
management, from generating a 24-word mnemonic to deploying ERC-4337 accounts
with programmable spending rules.

| Library                    | Purpose                                                                                            |
| -------------------------- | -------------------------------------------------------------------------------------------------- |
| `@aje/wallets`             | HD wallets (BIP-32/39/44), MPC wallets, session keys, hardware wallet integration (Ledger, Trezor) |
| `@aje/account-abstraction` | ERC-4337, EIP-7702, ERC-7579, ERC-6900, bundler integration, paymaster services                    |

### DeFi and Finance Layer

These five packages cover the financial protocol integrations — from AMM swaps
and lending to oracle price feeds and prediction markets.

| Library            | Purpose                                                                                            |
| ------------------ | -------------------------------------------------------------------------------------------------- |
| `@aje/defi`        | Uniswap, Curve, Balancer, Aave, Compound, MakerDAO, yield aggregators, liquid staking, derivatives |
| `@aje/payments`    | Stablecoins, Circle API, fiat on/off ramps, streaming payments (Superfluid, Sablier)               |
| `@aje/oracles`     | Chainlink, Pyth, RedStone, API3 price feeds; custom oracle construction                            |
| `@aje/predictions` | Polymarket, custom prediction market contracts                                                     |
| `@aje/restaking`   | EigenLayer, AVS development, LRT protocols                                                         |

### Asset Layer

These three packages deal with on-chain asset representations — NFTs, tokenised
real-world assets, and the decentralised storage systems that back their
metadata.

| Library        | Purpose                                                                                               |
| -------------- | ----------------------------------------------------------------------------------------------------- |
| `@aje/nft`     | ERC-721/721A/1155, token-bound accounts (ERC-6551), soulbound tokens, dynamic NFTs, royalty standards |
| `@aje/rwa`     | Real-world asset tokenization (ERC-3643), treasury bonds, compliance                                  |
| `@aje/storage` | IPFS, Filecoin, Arweave; NFT metadata pipelines                                                       |

### Protocol Layer

These five packages operate at the smart contract protocol level — compiling and
deploying contracts, bridging assets between chains, expressing intent-based
transactions, running governance, and managing decentralised identity.

| Library           | Purpose                                                                     |
| ----------------- | --------------------------------------------------------------------------- |
| `@aje/contracts`  | Contract compilation, deployment, upgrades, verification, testing utilities |
| `@aje/bridges`    | LayerZero, Wormhole, CCIP, Axelar, Avalanche Warp bridging                  |
| `@aje/intents`    | CoW Protocol, UniswapX, Across intent-based transactions                    |
| `@aje/governance` | Governor contracts, Snapshot, Tally, Aragon DAOs                            |
| `@aje/identity`   | DID, Verifiable Credentials, ENS, Lens, Farcaster, attestations             |

### Infrastructure Layer

These four packages provide the operational backbone for running reliable
blockchain infrastructure — node management, security tooling, ZK proof
generation, and privacy primitives.

| Library         | Purpose                                                                           |
| --------------- | --------------------------------------------------------------------------------- |
| `@aje/nodes`    | RPC provider management, full node config, validator integration, light clients   |
| `@aje/security` | Static analysis, formal verification, MEV protection, access control verification |
| `@aje/zkp`      | Circom circuits, Groth16/PLONK/FFLONK, Semaphore, ZKML, verifier generation       |
| `@aje/privacy`  | Privacy pools, FHE, MPC, TEE integration patterns                                 |

### Ecosystem Layer

These eight packages cover specialised blockchain ecosystems and the developer
tooling that ties everything together. `@aje/sdk` sits at the top of the
dependency tree as the public composition surface; `@aje/settlement-escrow` is a
narrow integration point for the Concordia domain.

| Library                  | Purpose                                                                                              |
| ------------------------ | ---------------------------------------------------------------------------------------------------- |
| `@aje/bitcoin`           | Lightning Network, Ordinals, Runes, Stacks, BitVM, RGB protocol                                      |
| `@aje/sui-move`          | Sui network, Move language, DeFi primitives, Aptos                                                   |
| `@aje/appchains`         | Rollup-as-a-Service: Conduit, Caldera, AltLayer, OP Stack, Orbit                                     |
| `@aje/gaming`            | MUD framework, World Engine, on-chain game assets                                                    |
| `@aje/depin`             | Compute, wireless, IoT, energy, location DePIN networks                                              |
| `@aje/agents`            | AI blockchain agents, x402 micropayments, safety controls                                            |
| `@aje/sdk`               | Composition layer: `core`, `react`, `python`, `cli`, `docs` sub-modules                              |
| `@aje/settlement-escrow` | Maps Concordia `escrow_release` clauses to chain-ready Aje escrow deployment plans (Phase 179.7.2.4) |

---

## Individual Library Structure

Every Aje library follows a consistent Nx project layout. Knowing this layout
makes it straightforward to navigate any unfamiliar package: `src/index.ts` is
always the public API entry point, and `*.spec.ts` files sit next to the modules
they test.

```
libs/aje/<library>/
  package.json             # Name, version, ESM exports, dependencies
  project.json             # Nx configuration (build, lint, test targets)
  tsconfig.json            # Extends tsconfig.base.json
  tsconfig.lib.json        # Library compilation config
  tsconfig.spec.json       # Test compilation config
  vitest.config.ts         # Vitest configuration
  src/
    index.ts               # Public API barrel export
    types.ts               # TypeScript type definitions (per module)
    *.ts                   # Implementation modules
    *.spec.ts              # Vitest test suites, co-located with modules
```

Vitest `*.spec.ts` files are co-located with the modules they test inside `src/`
rather than in a separate `tests/` directory.

---

## Cryptographic Architecture

Cryptography is one of the highest-stakes areas of the domain — a single
implementation mistake can result in irreversible loss of funds. The diagram
below shows the exact library dependencies underpinning `@aje/core`'s
cryptographic surface. Every operation delegates to an externally audited
library; no custom curve or hash code exists anywhere in the domain.

```
@aje/core cryptographic dependencies:

@noble/hashes          → SHA-256, SHA-512, Keccak-256, BLAKE2b, RIPEMD-160
@noble/curves          → secp256k1 (EVM/Bitcoin), ed25519 (Solana), BLS12-381
@scure/base            → base58, base64, hex, bech32 encoding
@scure/bip32           → HD key derivation (BIP-32)
@scure/bip39           → Mnemonic generation and validation (BIP-39)
@oshun/crypto          → shared workspace crypto package
node:crypto            → AES-128-CTR for the encrypted-keystore module
```

`@aje/core` exposes a typed cryptographic surface (hashing, secp256k1/ed25519/
BLS/Schnorr signatures, AES-GCM/ECIES encryption, PBKDF2/scrypt, BIP-39/BIP-32
HD derivation) that higher-level packages are expected to consume. Several
packages — including `@aje/bitcoin`, `@aje/bridges`, `@aje/nft`, `@aje/wallets`,
and `@aje/zkp` — additionally declare `@noble/*` / `@scure/*` as direct
dependencies for chain- or protocol-specific cryptography. No package implements
its own curve or hash primitives.

---

## Multi-Chain Provider Architecture

Supporting multiple blockchains is one of the central design challenges in Aje.
`@aje/chains` solves it by exporting a separate named namespace for each
supported chain, all implementing the same `ChainProvider` interface. The
abstraction namespace provides the unified registry and transaction builder that
application code uses when it doesn't need to know which chain it's on. Note
that Sui and Move support live in the separate `@aje/sui-move` package rather
than inside `@aje/chains`, because the Move ecosystem's development toolchain is
distinct enough to warrant its own package boundary.

```
@aje/chains
├── ethereum/           → JSON-RPC provider, WebSocket, Multicall3, Flashbots, debug/trace
├── arbitrum/           → L2 provider, gas, L1-L2 messaging, bridge, Orbit, Stylus
├── optimism/           → OP Stack provider, gas, messaging, bridge (Optimism, Base)
├── zksync/             → zkSync Era, EIP-712 transactions, paymasters, native AA, ZK Stack
├── polygon/            → Polygon PoS + zkEVM, Linea, Scroll, Starknet, multi-L2 routing
├── avalanche/          → C/X/P chains, subnets, cross-chain, AWM/Teleporter, custom VMs
├── cardano/            → UTxO model, Plutus, Hydra L2, CIP-1694 governance
├── solana/             → RPC, transactions, SPL tokens, programs, Anchor IDL, Jito
└── abstraction/        → Unified ChainProvider interface, ChainRegistry,
                          TransactionBuilder, AddressResolver, UnifiedProvider
```

---

## Design Patterns

### Pure Functions for Core Operations

All cryptographic functions in `@aje/core` are stateless pure functions. Given
the same inputs, they always produce the same outputs. This makes them trivially
testable and safe to call from any context.

### Chain-Specific Modules, Unified Interface

Each chain's provider is a named module within `@aje/chains` that implements the
`ChainProvider` interface. Application code uses the interface; chain-specific
behavior is encapsulated. Adding a new chain requires only implementing the
interface in a new module.

### Typed ABI Encoding

ABI encoding/decoding in `@aje/core` is fully typed using the TypeScript type
system. Function selectors, parameter types, and return types are inferred from
ABI definitions at compile time — no runtime type errors from ABI mismatches.

### Composition-Layer SDK

`@aje/sdk` is a composition layer exposing five sub-modules — `core` (provider,
signer, contracts, transactions, retry, bundling), `react` (context, connectors,
hooks, a wagmi-compatibility shim), `python` (a TypeScript generator for Python
bindings and packaging), `cli`, and `docs`. It declares `@aje/core` and
`@aje/chains` as peers. Consumer dApps import from `@aje/sdk` for a coherent
developer surface rather than wiring each package directly.

---

## Cross-Domain Dependencies

Aje is a foundational domain: it depends on a small number of shared workspace
packages, and several other Oshun domains depend on it. The table below lists
every cross-domain dependency together with the reason the boundary exists.

The outbound dependencies (`aje → shared` and `aje → concordia`) exist because
Aje deliberately avoids re-implementing infrastructure that other domains
already own. `@oshun/crypto` is the workspace-wide crypto package that Aje
builds on top of; `@oshun/database` owns the SQL helper primitives that
`@aje/database` uses to emit queries; `@concordia/contracts` exposes the
Concordia domain's clause types that `@aje/settlement-escrow` must validate
against.

The inbound dependencies (`V2 → aje`) exist because the V2 game project needs
blockchain capabilities — specifically wallet-bound cosmetic ownership and
fan-token governance — but those features are narrow opt-in surfaces with strict
safety envelopes. Aje owns the wallet, NFT, and governance primitives; V2 owns
the safety boundary (user warnings, platform cert-ban checks).

Aje does not depend on a message broker or logging package, and publishes no
event-bus messages — no Aje package imports `@oshun/event-bus`.

| Dependency                  | Direction       | Purpose                                                               |
| --------------------------- | --------------- | --------------------------------------------------------------------- |
| `@oshun/crypto`             | aje → shared    | Workspace crypto package; runtime dependency of most Aje packages     |
| `@oshun/types`              | aje → shared    | Optional peer dependency of `@aje/core`                               |
| `@oshun/database`           | aje → shared    | Peer of `@aje/database`; provides `sql`/`sqlRaw`/`ParameterizedQuery` |
| `@concordia/contracts`      | aje → concordia | Runtime dependency of `@aje/settlement-escrow`                        |
| `@aje/identity`, `@aje/nft` | V2 → aje        | Consumed by `@v2/aje-web3-cosmetic-ownership`                         |
| `@aje/governance`           | V2 → aje        | Consumed by `@v2/aje-faction-governance`                              |
