docs/domains/aje/ (API notes, ADRs, deep topic guides) — reconciled here by linking, kept beside the code as supporting material rather than a second canonical source (§2, §13).Aje is the blockchain, DeFi, and Web3 infrastructure domain of the Oshun monorepo. 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 — Aje provides 31 libraries spanning the complete Web3 stack: wallet management (HD wallets, MPC threshold signing, hardware wallets, ERC-4337 account abstraction), multi-chain network support (Ethereum L1 and L2 ecosystem, Solana, Cardano, Avalanche, Sui/Aptos), DeFi protocol integration (AMMs, lending, yield, derivatives), NFT infrastructure, smart contract tooling, zero-knowledge proofs, cross-chain bridges, decentralised identity, on-chain governance, oracle integration, real-world asset tokenisation, decentralised physical infrastructure networks, AI blockchain agents, prediction markets, liquid restaking, privacy infrastructure, intent-based architecture, on-chain gaming infrastructure (MUD framework, World Engine, autonomous worlds), and a dedicated Sui/Move ecosystem library. Aje is the financial and decentralised protocol backbone for the entire Oshun platform.
Aje exists as a library-only domain: it ships no applications or services of its
own. Every capability described in this document is a set of composable
TypeScript libraries that other domains and services import to gain blockchain
functionality. A consuming domain never needs to re-implement wallet key
derivation, ABI encoding, or oracle integration — it imports the appropriate
@aje/* package and builds on top of it.
The 31 libraries cover the full Web3 stack from the lowest-level crypto primitives up through domain-specific integrations. The sections below document each library's features in depth, starting with the foundation packages and working outward to the ecosystem and developer-facing layers.
Core Blockchain Primitives (@aje/core)#
The foundation types, utilities, and abstractions used across all Aje libraries.
- Address Types and Validation: Typed representations of addresses across all supported blockchains — EVM addresses (20-byte hex, EIP-55 mixed-case checksum), Solana public keys (base58 Ed25519), Cardano bech32 addresses, Sui object IDs, Bitcoin addresses (P2PKH, P2SH, P2WPKH, P2WSH, P2TR Taproot). Validation enforces the correct format per chain, preventing silent cross-chain address misuse.
- Transaction Abstractions: Unified transaction builder with chain-specific signing strategies — EVM RLP-encoded transactions, Solana versioned transactions (v0 with address lookup tables), Cardano CBOR transactions with UTxO model. The abstraction layer enables code that operates on transactions without caring about the underlying chain serialisation format.
- Cryptographic Primitives: Secp256k1 (used by Bitcoin and Ethereum),
Ed25519 (used by Solana, Cardano), BLS12-381 (used in Ethereum 2.0 consensus
signatures) — all using audited
@noble/curvesimplementations with no custom cryptographic code. Using audited libraries for cryptography is non-negotiable in financial systems. - ABI Encoding/Decoding: Ethereum ABI (Application Binary Interface) encoding and decoding for function calls, event logs, and constructor arguments — the wire format for all Ethereum contract interaction. Typed ABI encoding prevents the common vulnerability class of incorrectly encoding function arguments.
- Hash Functions: keccak256 (Ethereum's primary hash), SHA-256, SHA-3, Blake2b, and Poseidon (ZK-circuit-friendly hash) implementations, all from audited libraries.
- Gas Estimation Utilities: Base fee + priority fee modelling for EIP-1559 transactions, gas limit estimation from simulated execution, and historical gas price percentile analysis for optimal fee selection.
Wallet Management (@aje/wallets)#
HD Wallet Generation and Derivation#
Hierarchical Deterministic (HD) wallets derive unlimited key pairs from a single master seed, enabling a complete multi-account, multi-chain wallet from one 12–24 word mnemonic backup.
- BIP-39 Mnemonic Generation: 12, 15, 18, 21, or 24-word seed phrase generation using CSPRNG entropy and the BIP-39 word list. Each word encodes 11 bits of entropy from a 2048-word list. A 24-word mnemonic encodes 264 bits of entropy — computationally infeasible to brute-force.
- Multi-Chain HD Derivation: BIP-32 hierarchical key tree derivation using
hardened and non-hardened child keys. Standard BIP-44 derivation paths
(
m/44'/coin_type'/account'/change/index) for EVM, Bitcoin, and other chains. BIP-84 (m/84'/...) for native SegWit (P2WPKH), BIP-86 for Taproot (P2TR). - Multi-Account Management: A single seed generates independent key streams for unlimited accounts per chain. Account 0 for personal spending, Account 1 for business, Account 2 for DeFi — all recoverable from one backup.
- BIP-39 Passphrase Support: An optional BIP-39 passphrase ("25th word") is mixed with the seed before key derivation, producing a completely different wallet from the same mnemonic. This enables plausible deniability — a "honeypot" wallet on the empty passphrase, real funds on the passphrase-protected derivation.
Key Management and Security#
- Encrypted Keystore: AES-128-CTR (Ethereum v3 keystore format) encrypted keystore files with configurable key derivation functions — scrypt (memory-hard, resistant to GPU cracking) or PBKDF2. The encrypted keystore can be safely exported and stored.
- Shamir's Secret Sharing: Split a wallet's master secret into N shares where any K shares (K ≤ N, configurable) can reconstruct the secret — but K-1 shares reveal nothing. This enables threshold custody: 3-of-5 shares distributed across trusted parties, requiring compromise of 3 custodians before funds are at risk.
- Automated Key Rotation: Policies defining when keys should be rotated (time-based or event-triggered), with transition periods during which old and new keys are both valid, enabling seamless rotation without service interruption.
Multi-Party Computation (MPC) Wallets#
MPC wallets eliminate the single-point-of-failure in key custody by distributing the private key across multiple parties who must cooperate to sign — no single party ever has the full key.
- Threshold Signature Schemes (TSS): A t-of-n threshold signature scheme where n parties each hold a key share, and any t of them can collaborate to produce a valid signature — without any party ever learning the full key. The signature looks identical to a single-party signature on-chain, preserving privacy.
- Distributed Key Generation (DKG): A secure multi-party protocol where n parties jointly generate a key pair such that the private key is never assembled in one place — each party ends up with only their share.
- Proactive Key Share Refresh: Periodically re-randomise all key shares without changing the underlying key. A compromised share from before the refresh cannot combine with current shares to attack the key.
- Ceremony Lifecycle Management: Full orchestration for DKG setup ceremonies and ongoing signing ceremonies — invitation, participation, round-trip communication, and final aggregation.
Smart Account Abstraction (ERC-4337)#
ERC-4337 separates the concept of a blockchain account from the cryptographic key that controls it, enabling programmable spending rules, gas sponsorship, and account recovery — all without changes to the Ethereum protocol itself.
- Smart Contract Account Deployment: Deploy ERC-4337-compatible smart contract wallets (Safe, Kernel, Biconomy, Alchemy Light Account) for any address.
- UserOperation Construction: Build and sign EIP-4337
UserOperationobjects — the higher-level transaction format that goes through the bundler mempool rather than the standard transaction mempool. - Bundler Integration: Submit UserOperations to bundler services (Alchemy, Pimlico, Stackup), track confirmation status, and handle bundler-specific error codes.
- Paymaster Services: Verifying paymaster (platform sponsors specific transactions), token paymaster (user pays gas in ERC-20 tokens instead of native ETH), NFT-gated sponsorship (holders of a specific NFT get free gas), and subscription paymaster (monthly gas allowance). Gas abstraction is one of the key UX improvements for mainstream Web3 adoption.
- Session Keys: Scoped temporary keys with limited permissions — a gaming session key can execute in-game transactions but cannot transfer funds. Time-bounded, value-limited, and action-limited delegation for dApp interactions.
Hardware Wallet Integration#
- Ledger Support: USB and Bluetooth transport to Ledger Nano S/X/Stax devices. Blind signing prevention — all transaction details are displayed on the hardware device screen before signing. Multi-chain support: Ethereum, Bitcoin, Solana, and other supported coins.
- Trezor Support: Trezor Model T and Trezor One via WebUSB and HID transport. Full multi-chain transaction signing with on-device confirmation.
Multi-Chain Network Support (@aje/chains)#
Ethereum Mainnet and Layer 2 Ecosystem#
The Ethereum ecosystem is the dominant smart contract platform. "Layer 2" (L2) solutions process transactions off the main chain and submit proofs or compressed data back to Ethereum (L1) for security.
- Ethereum L1: JSON-RPC provider with WebSocket subscription for real-time block events. Multicall3 aggregation (batch dozens of read calls into a single RPC request). Flashbots bundle submission for MEV (Maximal Extractable Value) protection — submitting transactions directly to block builders bypasses the public mempool where front-runners monitor for profitable opportunities.
- Arbitrum (Nitro): Optimistic rollup L2 with sub-second block times and ~10× lower gas costs than L1. OP Stack architecture compresses L1 calldata by posting batch compressed transactions.
- Optimism and Base: Optimism's OP Stack powers both Optimism mainnet and Coinbase's Base L2. The Superchain vision — many OP Stack chains sharing a common sequencer and bridge — is relevant to Aje's cross-chain architecture.
- zkSync Era: Zero-knowledge rollup with native account abstraction (AA is built into the protocol, not a bolt-on). EIP-712 structured data signing, zk-SNARK proof generation for batches, and native paymaster integration.
- Polygon PoS and zkEVM: Polygon's Proof-of-Stake chain (high throughput, lower security than L1) and Polygon zkEVM (Ethereum-equivalent ZK rollup). Both widely used in gaming and DeFi applications.
- Starknet: Cairo VM-based ZK rollup with its own non-EVM execution environment. Supports native account abstraction and is used by major trading protocols and gaming applications.
- Additional L2s: Linea (Consensys zk-rollup), Scroll (open-source ZK-EVM), Mantle, Blast, and Mode Network — all included in the chain registry with RPC endpoint management.
Alternative Layer 1 Networks#
- Solana: High-throughput non-EVM L1 with sub-second finality and ~$0.00025 transaction fees. Aje supports Solana RPC client with account subscription, SPL token program interaction (the Solana equivalent of ERC-20), Anchor framework IDL parsing for typed program interaction, and Jito bundle submission for MEV-protected transactions.
- Cardano: UTxO (Unspent Transaction Output) model — fundamentally different from Ethereum's account model. Each input must be explicitly referenced; all outputs must be consumed. Plutus V2/V3 smart contracts using Haskell-like lambda calculus. Hydra L2 for off-chain payment channels. CIP-1694 on-chain governance for the Cardano treasury.
- Avalanche: Three-chain architecture — C-Chain (EVM-compatible, runs smart contracts), X-Chain (asset exchange, UTXO model), P-Chain (validator coordination). Subnet creation for application-specific blockchains using Avalanche consensus. Avalanche Warp Messaging for native cross-subnet communication.
- Sui: Move language VM (designed for safe resource ownership) with Sui's object-centric data model. Objects are the primitive — every on-chain entity is an owned or shared object. The Aje library provides Sui RPC client, Move call builder, and DeFi primitive interfaces. Aptos (sister chain using Move) is also supported.
Chain Abstraction Layer#
- Unified Provider Interface: A single
ChainProviderinterface wraps all supported chains. Application code interacts with one API regardless of whether the underlying chain is EVM, Solana, Cardano, or Sui — the provider handles serialisation, fee estimation, and confirmation polling. - Chain Registry: Metadata for all supported chains — chain ID, native token symbol, RPC endpoint templates, explorer URLs, average block time, and finality model.
- Cross-Chain Transaction Builder: Construct transactions that span multiple chains — e.g., approve an ERC-20 on Ethereum, bridge to Arbitrum via the native bridge, then interact with a DeFi protocol on Arbitrum — all in a single typed builder pipeline.
DeFi Protocol Integration (@aje/defi)#
DeFi (Decentralised Finance) protocols are smart contract systems that replicate financial primitives (exchange, lending, derivatives) without trusted intermediaries.
Automated Market Makers (AMM)#
AMMs use mathematical formulas to set prices between token pairs, replacing traditional order books with liquidity pools.
- Uniswap V2/V3/V4: V2 uses the constant product formula (x × y = k); V3 concentrates liquidity in configurable price ranges for capital efficiency; V4 introduces hooks (custom logic at any point in a swap's lifecycle) and a singleton pool architecture. Aje integrates swap quote generation, optimal route finding across multiple pools, liquidity position management (including NFT position tokens in V3), and fee tier selection.
- Curve Finance: Specialised AMM for correlated assets (stablecoins, liquid staking tokens) using the StableSwap invariant, which provides near-zero slippage for equal-price assets. Aje integrates all pool types — stable pools (3pool: USDC/USDT/DAI), crypto pools (volatile asset pairs with dynamic fee), factory pools (permissionless deployment), and yield optimisation strategies via CRV rewards.
- Balancer V2/V3: Generalised AMM supporting N-token pools with arbitrary weights (e.g., 80% ETH / 20% BAL). Boosted pools that deposit idle liquidity into Aave/Compound for additional yield. Aje integrates weighted pool management, composable stable pool interaction, and the Balancer vault's internal token accounting.
- Odos and 1inch Aggregation: Smart order routing across all AMMs to find the best execution price, splitting trades across multiple pools when beneficial.
Lending Protocols#
Lending protocols enable permissionless collateralised borrowing — deposit crypto as collateral, borrow against it.
- Aave V3: The largest lending protocol by TVL. Supply assets to earn interest; borrow against supplied collateral up to a loan-to-value (LTV) limit. Flash loans — borrow any amount in a single transaction without collateral, as long as the loan is repaid within the same transaction — enable capital-free arbitrage and liquidation automation. Aje supports all Aave actions: supply, withdraw, borrow, repay, flash loan, interest rate switching, and multi-collateral position management.
- Compound V3 (Comet): Upgraded architecture where each market has a single base asset (e.g., USDC) and multiple collateral assets. Simplified position management with continuous compound interest. Governance participation via COMP token voting.
- MakerDAO: The original decentralised stablecoin protocol — deposit ETH or other collateral into a Collateralised Debt Position (CDP) and generate DAI (target: $1.00) against it. Stability fees accrue to the Maker treasury. Aje integrates CDP creation, management, DAI minting/burning, and stability fee monitoring.
Yield and Staking#
- Yield Aggregators: Yearn Finance (vaults that auto-compound rewards), Convex (CVX rewards on top of Curve LP positions), and Aura Finance (AURA rewards on Balancer LP positions) — all integrated with deposit, withdraw, and reward harvesting flows.
- Liquid Staking Tokens: When ETH is staked in Ethereum's Proof-of-Stake consensus, it is locked until withdrawals were enabled (now enabled post-Shanghai). Liquid staking derivatives give stakers a tradeable token that represents their staked ETH plus accrued rewards: stETH (Lido), rETH (Rocket Pool, decentralised), frxETH (Frax ETH). Aje integrates staking, unstaking, and staking position management for all three.
Derivatives and Advanced DeFi#
- Perpetuals: Perpetual swap contracts that mimic leveraged futures positions without expiry. dYdX (order-book based), GMX (oracle-price based with GLP liquidity), and Synthetix (synthetic assets backed by SNX collateral). Aje integrates position opening/closing, funding rate monitoring, and liquidation management.
- Options: Lyra (on Arbitrum/Optimism) and Dopex — decentralised options protocols. Aje integrates option buying, writing, and settlement.
- MEV Protection: Private RPC routing (Flashbots Protect, MEV Blocker, SecureRPC) that submits transactions directly to block builders without exposing them to the public mempool where sandwich bots exploit price impact. Essential for any DeFi transaction of meaningful size.
NFT Infrastructure (@aje/nft)#
NFTs (Non-Fungible Tokens) are on-chain representations of ownership — each token has a unique ID, making them suitable for representing ownership of art, collectibles, game items, real estate titles, and any asset with individual identity.
- ERC-721 Standard: The original NFT standard — one token ID per owner per contract. Full lifecycle: mint, transfer, approve operator, safe transfer with receiver hook, tokenURI metadata (JSON pointing to name, description, image, and attributes).
- ERC-721A (Gas-Optimised Batch Minting): Azuki's gas optimisation for minting multiple NFTs in a single transaction — reduces minting gas by ~90% for batch sizes, critical for large collection launches.
- ERC-1155 Multi-Token Standard: A single contract manages both fungible tokens (e.g., in-game gold — all identical) and non-fungible tokens (unique items) — reducing deployment costs and enabling batch transfers of mixed token types.
- Token-Bound Accounts (ERC-6551): NFTs that own assets — any ERC-721 token can be given its own smart contract account. An NFT character in a game can hold its own inventory NFTs, accumulate token rewards, and interact with DeFi protocols, all while remaining transferable as a single asset.
- Soulbound Tokens (ERC-5192): Non-transferable tokens that cannot be moved once minted. Used for credentials, certifications, governance participation rights, and identity attestations that should be tied to a specific person rather than tradeable.
- Dynamic NFTs: NFTs whose metadata changes on-chain or off-chain over time — a game character NFT whose stats update as the player levels up, or an art NFT whose appearance changes based on external data (weather, price feeds, events).
- Royalty Standards (ERC-2981): On-chain royalty information — creator address and fee percentage — readable by any marketplace. The Manifold royalty registry provides an alternative for overriding royalty enforcement across marketplaces.
- Marketplace Integration: OpenSea Seaport v1.5, Blur (the dominant secondary market for professional NFT traders), and LooksRare — with order creation, cancellation, fulfillment, and collection offer management.
- Collection Analytics: Floor price, 24h/7d/30d volume, holder distribution (top 10, unique holders, whale concentration), and listing depth — providing market intelligence for collection management.
Smart Contract Development (@aje/contracts)#
- Compilation via Foundry and Hardhat: Both Foundry (Rust-based, fast) and Hardhat (JavaScript, rich ecosystem) compilation backends are supported. The library normalises compiler output into a consistent format.
- Deployment Flows: Deterministic deployment via CREATE2 (the deployed address is a function of the deployer address, salt, and bytecode — computed in advance before deployment), allowing cross-chain address consistency. Proxy pattern deployment (UUPS, Transparent Proxy, Minimal Proxy EIP-1167) for upgradeable contracts.
- Upgrade Management: OpenZeppelin's Hardhat upgrades plugin integrated for checking storage layout compatibility before upgrades — preventing the storage collision vulnerabilities that have drained millions from upgradeable contracts.
- Contract Verification: Automated verification on Etherscan (and all Etherscan-compatible block explorers), Sourcify (decentralised verification), and Blockscout. Verified source code is essential for user trust.
- Testing Utilities: Mock contract generation, snapshot testing (save/restore state), and fuzz testing (generate random inputs to discover edge cases) — both Foundry-native and Hardhat/Chai compatible.
- TypeScript Binding Generation: Generate fully typed TypeScript classes from contract ABIs using TypeChain or Wagmi's code generation, eliminating the runtime errors that come from manually encoding function calls.
- Gas Optimization Analysis: Storage packing analysis, function selector collision detection, and inline assembly suggestions to reduce gas costs in frequently called contracts.
Cross-Chain Bridges (@aje/bridges)#
Cross-chain bridges move assets and messages between different blockchains. Each bridge has different security models, trust assumptions, and speed trade-offs.
- LayerZero V2: An omnichain messaging protocol where "Ultra Light Nodes" verify messages using configurable security stacks (DVNs — Decentralised Verifier Networks). The OFT (Omnichain Fungible Token) standard extends ERC-20 across any chain in the LayerZero network — burn on source, mint on destination, with no wrapped tokens. Aje integrates send/receive message flows, DVN configuration, and OFT deployment and management.
- Wormhole: A cross-chain messaging protocol secured by 19 Guardian nodes. VAAs (Verified Action Approvals) are the signed attestation format. Aje integrates token bridging (with wormhole-wrapped tokens), VAA verification, and the Wormhole SDK.
- Chainlink CCIP (Cross-Chain Interoperability Protocol): Chainlink's battle-tested oracle network extended to cross-chain messaging. Security backed by Chainlink's established oracle operator network. Aje integrates token transfer and arbitrary message passing via CCIP.
- Axelar Network: General Message Passing protocol with its own proof-of-stake validator set. Supports token transfers and executable messages (trigger contract function on destination chain). Used by major DeFi protocols for cross-chain governance and liquidity.
- Bridge Route Optimization: Given a source chain, destination chain, asset, and amount, the library finds the optimal bridge path considering fee, speed, and security trade-offs — outputting a ranked list of routes with cost estimates.
Zero-Knowledge Proofs (@aje/zkp)#
Zero-knowledge proofs allow one party (the prover) to convince another (the verifier) that a statement is true without revealing anything other than the truth of the statement. They are transformative for both privacy and scalability.
- Circom Circuit Compilation: Circom is the dominant DSL (domain-specific
language) for writing ZK circuits. A circuit defines the arithmetic
constraints that must be satisfied by a valid witness (the private input). The
library compiles
.circomfiles and generates the proving and verifying keys. - Groth16 Proving System: The most widely deployed ZK-SNARK (Succinct Non-interactive ARgument of Knowledge). Produces constant-size proofs (~200 bytes) regardless of circuit size, verifiable in a few milliseconds on-chain. Requires a trusted setup ceremony — the "toxic waste" from the ceremony must be destroyed, which is why Groth16 ceremonies involve hundreds of participants.
- PLONK and FFLONK: Universal ZK-SNARK proving systems that do not require a circuit-specific trusted setup — a single universal structured reference string works for all circuits below a maximum size. Slower proof generation than Groth16 but far more flexible.
- zk-STARKs: ZK proofs that require no trusted setup (they are "transparent") and are post-quantum secure (not vulnerable to Shor's algorithm if large quantum computers are ever built). Larger proofs than SNARKs (~45 KB) but no trusted setup risk. Used by StarkWare (StarkEx, Starknet) for L2 scaling.
- Semaphore: A ZK protocol for anonymous group membership. A group member can signal (vote, post, etc.) without revealing which member they are — only proving they are a valid member. The basis of many anonymous governance and reputation systems.
- ZKML (Zero-Knowledge Machine Learning): Prove that a specific ML model inference was run correctly on specific inputs, producing a specific output — without revealing the model weights or the inputs. Enables verifiable AI in privacy-preserving contexts.
- Proof Generation with GPU Acceleration: ZK proof generation is compute-intensive. The library supports GPU-accelerated proving for NVIDIA (CUDA) and Apple Silicon (Metal) using GPU-optimised MSM (Multi-Scalar Multiplication) and NTT (Number Theoretic Transform) implementations.
- On-Chain Verifier Contract Generation: Automatically generate the Solidity verifier contract for any given proving system and circuit, deployable directly to Ethereum or any EVM-compatible chain.
Decentralised Identity (@aje/identity)#
Decentralised identity enables self-sovereign, user-controlled identity without dependence on any single organisation.
- W3C DIDs (Decentralised Identifiers): DIDs are URIs (like
did:ethr:0x...) that resolve to DID Documents describing the subject's public keys, service endpoints, and verification methods — without a central registry. Aje implements DID creation, resolution, and updating fordid:ethr,did:key, anddid:webmethods. - Verifiable Credentials (VC): W3C Verifiable Credentials are cryptographically signed claims about a subject — a degree credential, age proof, KYC status, or professional certification — issued by a trusted party and verifiable by anyone with the issuer's public key. Aje implements credential issuance, presentation, and verification using JSON-LD proofs and JWT signatures.
- ENS (Ethereum Name Service): ENS maps human-readable names (alice.eth) to Ethereum addresses, IPFS content hashes, and other resources. Aje integrates name resolution (looking up the address for any .eth name), name registration, and record management (setting avatar, email, social profiles, and contenthash records).
- Lens Protocol: A composable social graph protocol — profiles, follows, posts, collects, and comments are all on-chain primitives that any app can build on. Aje integrates profile creation, follow/unfollow, and collect flows.
- Farcaster: A decentralised social network where user data lives on a distributed network of "Hubs" rather than a central server. Aje integrates with the Farcaster Hub API for reading and writing casts (posts), reactions, and follow relationships.
- Social Recovery: Guardian-based account recovery systems where trusted friends/family/institutions can vote to reassign control of a smart account, providing a path out of the catastrophic key loss scenario that plagues raw key custody.
- EAS (Ethereum Attestation Service): A general-purpose on-chain and off-chain attestation system — any entity can make a claim about any other entity (address, ENS name, etc.) using a defined schema. Aje integrates attestation creation, querying, and revocation.
On-Chain Governance (@aje/governance)#
Governance protocols enable token holders to collectively control protocol parameters, treasury allocations, and upgrade decisions.
V2 consumes @aje/governance through @v2/aje-faction-governance for optional
fan-token faction votes. The V2 surface builds Snapshot ERC20 voting strategies,
faction spaces, and proposal payloads, but only after explicit opt-in and after
fan_token_gated_gameplay is cleared by the platform cert-ban table.
- OpenZeppelin Governor: The most widely deployed on-chain governance framework. Proposal creation (requires minimum token balance), voting period (configurable), quorum requirements, timelock delay before execution, and guardian veto. Aje integrates proposal submission, voting (for/against/abstain), vote delegation, and proposal execution.
- Snapshot.js Integration: Snapshot is a gasless off-chain voting platform — strategies sign votes using wallet keys, votes are stored on IPFS and indexed, and results are computed off-chain. Used by virtually every major DeFi protocol for governance signalling before on-chain execution.
- Tally API: Governance analytics and delegation management across all major Governor deployments — see who the top delegates are, how they vote, and delegate your votes to a trusted community participant.
- Aragon: A DAO (Decentralised Autonomous Organisation) creation framework — create a DAO with treasury, voting plugin, token, and permission management without writing custom smart contracts.
- Voting Strategies: Token-weighted (1 token = 1 vote), quadratic (1 token = √1 votes — reduces whale dominance), conviction voting (tokens locked for longer periods accumulate more voting power — rewards patient, long-term stakeholders), delegated (delegate your vote to a trusted community member who votes on your behalf), and time-weighted (rewards long-term holders over recent buyers).
- Timelock Controller: A mandatory delay between governance approval and execution, providing a window for users to exit if they disagree with a protocol change. The delay period (typically 24–72 hours) is a critical safety mechanism.
- Proposal Simulation: Fork the chain state at proposal creation time and simulate execution in an anvil/Tenderly fork before the actual execution transaction, catching parameter errors and unexpected state changes.
Oracle Integration (@aje/oracles)#
Oracles provide blockchains with external data — price feeds, randomness, weather data, sports results — that smart contracts need but cannot access natively (blockchains are deterministic systems that cannot make HTTP requests).
- Chainlink Data Feeds: The dominant oracle network for on-chain price data. Aggregates prices from multiple independent node operators, providing tamper-resistant price feeds for 1,000+ asset pairs. Chainlink VRF (Verifiable Random Function) provides cryptographically proven randomness — a verifiable proof that the random value was not manipulated. Proof of Reserve enables DeFi protocols to verify the backing of wrapped assets.
- Pyth Network: High-frequency price feeds aggregated from over 90 first-party data providers (trading firms and exchanges) using a pull model — users fetch the latest price when needed, paying only for the data they consume. Confidence intervals quantify uncertainty, enabling more sophisticated oracle consumers to adjust slippage tolerance based on data quality.
- RedStone Oracle: A modular oracle design supporting multiple data delivery methods — on-chain (standard), off-chain with on-demand pull, and a dedicated relayer model. Covers more exotic assets (DeFi LP tokens, yield-bearing tokens) than simpler oracles.
- API3: First-party oracle data — API providers run their own Airnode directly on-chain rather than going through a third-party oracle node. This eliminates the "middleware risk" of intermediary node operators.
- Custom Oracle Construction: Tools for building application-specific oracle aggregators — TWAP (Time-Weighted Average Price) from Uniswap V3 observations, multi-source median aggregation with outlier rejection, and circuit breakers that pause oracle output if price deviation exceeds a threshold.
- Oracle Manipulation Detection: The DeFi space has suffered billions in losses from oracle manipulation attacks (flash loan price manipulation to liquidate positions or drain lending protocols). The library provides detection utilities and circuit breaker patterns.
Payment Protocols (@aje/payments)#
- Stablecoin Integrations: USDC (Circle), USDT (Tether), DAI (MakerDAO), and FRAX (Frax Finance) — the four most widely used stablecoins. Each has different issuance mechanisms, regulatory profiles, and smart contract risks. The library provides minting/burning (where accessible), transfer, and balance management.
- Circle API and USDC: Circle's Programmable Wallets API for custodial USDC management — create wallets, initiate transfers, and manage USDC programmatically at scale. Relevant for platform fiat-to-crypto on-ramps.
- Fiat On/Off Ramps: Integration interfaces for MoonPay, Transak, and Stripe Crypto — services that convert fiat currency (credit card, bank transfer) to crypto and back. The library provides deeplink and widget integration patterns.
- Streaming Payments: Superfluid enables per-second token streams — a payroll contract that pays $100/month can instead stream $0.0000038/second continuously. Sablier provides vesting streams with configurable unlock schedules. Both are relevant for creator monetisation, payroll, and recurring subscription models.
- Payment Splitting Contracts: Multi-party revenue distribution — define revenue recipients with percentage splits, and any income automatically distributes to all parties on receipt. Used for royalty splitting, DAO treasury distribution, and multi-creator revenue sharing.
- Subscription Billing On-Chain: Automated recurring payment authorisation — a subscriber approves a maximum amount, and the subscription contract pulls the correct amount each billing period without requiring a new approval each month.
Decentralised Storage (@aje/storage)#
Decentralised storage systems provide content-addressed, censorship-resistant data persistence — key for NFT metadata, application data, and regulatory record-keeping that must survive platform shutdowns.
- IPFS (InterPlanetary File System): Content-addressed storage where a file's address is a hash (CID — Content Identifier) of its content — making it impossible to alter a file without changing its address. Aje integrates file uploading, pinning to keep files available (via Pinata, Infura IPFS, or web3.storage), CID resolution, and gateway management (converting IPFS CIDs to HTTP URLs via public or private gateways).
- Filecoin: A blockchain-based storage market where clients pay miners to store data for specified durations with cryptographic proof of storage (PoRep and PoSt — Proof of Replication and Proof of Spacetime). Aje integrates deal creation, retrieval market, and Lotus API interaction.
- Arweave: Permanent storage — a one-time payment funds storage indefinitely via Arweave's endowment model, where storage costs fall over time as hardware improves. Bundlr/Irys provides fast batch upload with instant availability and lazy settlement to Arweave. Arweave's GraphQL API enables rich querying of stored data.
- NFT Metadata Pipelines: Automated NFT metadata upload pipeline — images uploaded to IPFS/Arweave, metadata JSON generated from template, uploaded to same permanent storage, CID embedded in contract's tokenURI function. Ensures metadata persistence even if the original minter's infrastructure shuts down.
Security and Auditing (@aje/security)#
- Static Analysis Integration: Slither (Python-based Solidity static analyser) and Mythril output parsing — automated identification of common vulnerability classes: reentrancy (the vulnerability that drained the DAO in 2016), integer overflow/underflow, unchecked external calls, access control bugs, and price oracle manipulation patterns.
- Formal Verification Interfaces: Certora Prover and Halmos — tools that mathematically prove specific properties of smart contracts (e.g., "this function always reverts if the caller is not the owner") rather than merely testing them. These tools provide formal security guarantees, not probabilistic confidence.
- MEV Protection: Private RPC routing (Flashbots Protect, MEV Blocker) ensures transactions don't appear in the public mempool where searcher bots can observe them and insert sandwich transactions that worsen the user's execution price.
- Reentrancy Detection: Pattern analysis for reentrancy vulnerabilities in contract interaction code — the most common high-severity vulnerability class in Ethereum smart contracts.
- Signature Malleability Protection: EIP-712 typed structured data signing and Ethereum's ecrecover quirks — the library enforces canonical signatures and correct domain separator usage, preventing signature replay across contracts or chains.
- Audit Report Management: Structured storage and tracking of security audit reports, identified findings, remediation status, and recurring vulnerability patterns — creating an institutional memory for security posture.
Blockchain Data Persistence (@aje/database)#
- PostgreSQL DDL and Query Builders: Rather than wiring an ORM at runtime,
@aje/databaseemits PostgreSQLCREATE TABLE IF NOT EXISTSDDL and parameterized queries through@oshun/databasehelpers. It is organised into five namespaces —coreSchema(chains, blocks, transactions, receipts, event logs, contracts, tokens, NFTs, balances, allowances, gas-price history),walletSchema(wallets, account-abstraction accounts, session keys, multi-sig, DID documents, verifiable credentials, ENS cache, contacts, KYC, compliance),defiSchema(DEX swaps/volumes/fees, liquidity pools and positions, impermanent loss, lending, yield, portfolio),indexer, andmaintenance. - On-Chain Event Indexing: The
indexernamespace ingests EVM chain event logs into PostgreSQL (contract_events_index,token_transfers,subgraph_entities) with block-ingestion, contract-indexing, an API layer, and health monitoring, so application-level queries do not have to hit the RPC directly. - Transaction History: The
transactionsandtransaction_receiptstables carry per-address transaction history with status tracking (pending/submitted/confirmed/failed/dropped/replaced), gas used, value transferred, and input calldata. - Portfolio Snapshots: The
defiSchemaportfolio tables (portfolio_pnl,portfolio_snapshots) record balance and PnL snapshots for portfolio history and performance tracking. - DeFi Position Tracking:
lending_positions,liquidity_positions,yield_sources,reward_claims, and related tables record active DeFi positions, accrued rewards, and protocol TVL. - ORM-Schema Generator: The
maintenancenamespace includes a generator that emits Prisma or Drizzle schema source from an internal schema definition — a developer convenience, separate from how@aje/databaseitself talks to PostgreSQL.
@aje/database does not publish events. No Aje package integrates with an event
bus or message broker.
Real-World Asset Tokenisation (@aje/rwa)#
RWA (Real-World Asset) tokenisation represents off-chain financial assets — treasury bonds, real estate, private credit, commodities — as on-chain tokens, bringing liquidity and programmability to traditionally illiquid markets.
- ERC-3643 (T-REX Protocol): The permissioned token standard for compliant security tokens. Each holder must be whitelisted by an on-chain identity registry, and transfers are blocked unless both sender and recipient have verified KYC/AML status. Used by major tokenised fund issuers.
- Treasury Bond Tokenisation: Integration with tokenised T-bill products (BlackRock's BUIDL, Ondo Finance's OUSG, Franklin Templeton's FOBXX) — subscribe, redeem, and track yield from on-chain government bond positions.
- Real Estate Tokenisation: Fractional property ownership — a property is held in a special-purpose vehicle (SPV), the SPV issues tokens representing proportional ownership, and the tokens pay rental yield as smart contract distributions.
- Compliance Layer: On-chain KYC/AML verification, investor accreditation checks, jurisdictional transfer restrictions, and holding period locks — all enforced in contract logic.
- Yield Distribution Automation: Rental income, bond coupon payments, and dividend distributions automated through smart contracts — token holders receive pro-rata distributions without manual processing.
Node Management (@aje/nodes)#
- RPC Provider Management: Load balancing across multiple RPC providers (Alchemy, Infura, QuickNode, self-hosted) with failover. Latency-aware routing sends time-sensitive calls to the lowest-latency provider and batch queries to higher-latency but cheaper providers.
- Validator Client Integration: Ethereum consensus client interfaces (Lighthouse, Prysm, Teku) for solo staking operators — validator key management, deposit contract interaction, and withdrawal credential configuration.
- Light Client Support: Ethereum light clients (Helios) verify block headers and state proofs without downloading the full chain — viable in browser and mobile environments where a full node is impractical. Provides trustless RPC access without relying on a centralised provider.
- MEV-Boost Integration: MEV-Boost relay configuration for Ethereum validators — connecting to multiple MEV relays to maximise expected block value while maintaining censorship resistance guarantees.
Advanced Account Abstraction (@aje/account-abstraction)#
- EIP-7702: Allows an Externally Owned Account (EOA — a standard Ethereum address controlled by a private key) to temporarily delegate its transaction validation logic to a smart contract. This enables EOAs to benefit from smart account features (batching, gas sponsorship, session keys) without migrating to a fully new address.
- ERC-7579 (Modular Smart Account Standard): A standard for composable, modular smart accounts — separate execution modules, validation modules, hook modules, and fallback modules can be combined like building blocks to create custom account behaviour.
- ERC-6900 (Composable Plugin Framework): The Alchemy-proposed composable account standard where plugins define both validation logic and execution logic, enabling more powerful compositions.
- Bundler Integration: Alchemy's Rundler, Pimlico's Alto, and Stackup's erc4337-bundler — all supported with unified UserOperation submission and status tracking.
AI Blockchain Agents (@aje/agents)#
AI agents that can autonomously execute blockchain actions — representing the intersection of AI and DeFi.
- Autonomous Blockchain Agents: TypeScript agent framework where AI models (GPT-4, Claude, etc.) are given a toolkit of blockchain actions and can plan and execute multi-step on-chain strategies. Example: an agent that monitors DeFi yields and automatically rebalances between protocols.
- x402 Protocol: HTTP-native micropayments that allow AI agents to pay for API access, data, and services using cryptocurrency without requiring OAuth or credit cards. An agent making 1,000 small API calls pays per call rather than maintaining a subscription — the future of AI agent monetisation infrastructure.
- Composable Agent Tools: Standardised tool implementations that agents can
use —
swapTokens,bridgeAsset,stakeETH,voteOnProposal,deployContract,transferNFT— each with proper parameter validation and error handling. - Safety Controls: Spending limits per time period, action allowlists (only specific contract addresses and function selectors are callable), maximum gas per transaction, and human-in-the-loop approval for high-value or irreversible actions.
- Multi-Step DeFi Strategy Execution: Agents can execute strategies that require coordinated sequences — e.g., flash loan, swap at multiple pools, repay — all within a single transaction or over multiple blocks with state tracking.
Prediction Markets (@aje/predictions)#
Prediction markets are decentralised betting markets on future events — they aggregate information through financial incentives.
- Polymarket Integration: Polymarket is the dominant decentralised prediction market on Polygon. Aje integrates market data discovery, position management (buying and selling YES/NO outcome tokens), liquidity provision to the CLOB (Central Limit Order Book), and portfolio PnL tracking.
- Binary Outcome Markets: Smart contracts for YES/NO markets — a market resolves to 1 (YES wins) or 0 (NO wins), and outcome tokens pay $1 to winners. Conditional Token Framework (CTF) standard for composable market conditions.
- Multi-Outcome and Scalar Markets: Markets with more than two possible outcomes (election with multiple candidates) and scalar markets where the outcome is a numerical value in a range.
- Automated Market Makers for Prediction: Logarithmic Market Scoring Rule (LMSR) AMM that provides continuous liquidity for prediction markets, adjusting prices based on trading pressure.
- Resolution Oracles: UMA Optimistic Oracle (resolution is submitted and challenged if disputed), Reality.eth crowdsourced resolution (multiple humans vote on outcomes), and Chainlink-based automated resolution for objectively verifiable events.
- Market Analytics: Historical price evolution, trading volume, implied probability timeline, and trader concentration analysis.
Bitcoin Ecosystem (@aje/bitcoin)#
- Lightning Network: Bitcoin's Layer 2 payment channel network enabling instant, nearly-free micro-payments. Aje integrates invoice creation (BOLT11 format), payment routing (through the Lightning Network graph), channel management (open, close, force-close), and liquidity management.
- Bitcoin Ordinals: A protocol for inscribing arbitrary content (images, text, code) onto individual satoshis (the smallest Bitcoin unit, 1/100,000,000 BTC) by encoding data in witness data of SegWit transactions. Aje integrates inscription creation, indexing, and trading.
- Runes Protocol: A fungible token protocol for Bitcoin that uses OP_RETURN outputs to define and transfer tokens — a clean alternative to BRC-20 that avoids UTXO bloat.
- Stacks: A Bitcoin L2 that enables smart contracts (written in Clarity, a decidable language designed to prevent common contract vulnerabilities) that settle on Bitcoin. Aje integrates Clarity contract interaction and STX token management.
- BitVM: A cryptographic protocol enabling Bitcoin to verify arbitrary computation via optimistic fraud proofs — extending Bitcoin's programmability without a soft fork. BitVM enables a new class of Bitcoin L2 constructions.
- RGB Protocol: Client-side validated smart contracts and assets anchored to Bitcoin UTxOs. RGB assets live off-chain (only commitments are on Bitcoin) — extremely private and scalable, but requires recipient participation.
Decentralised Physical Infrastructure Networks (@aje/depin)#
DePIN networks coordinate real-world physical infrastructure through token incentives — paying participants to provide compute, wireless coverage, data, energy, or location services.
- Compute Networks: Akash Network (decentralised cloud compute market — bid for container workloads at below-AWS prices), Render Network (distributed GPU rendering for 3D, VFX, and AI inference). Aje integrates workload deployment, bidding, and payment flows.
- Wireless Networks: Helium (decentralised LoRaWAN and 5G wireless coverage — hotspot operators earn HNT for providing coverage and forwarding data) and XNET (decentralised 4G/5G network). Aje integrates device registration, hotspot management, and HNT/XNET earnings tracking.
- IoT Data Networks: Register IoT devices that sell sensor data (temperature, air quality, soil moisture, location data) on decentralised data marketplaces — Streamr, Syntropy — with micro-payment rails.
- Energy Networks: Power grid integration patterns for tokenised energy (RECs — Renewable Energy Certificates, peer-to-peer energy trading) and protocol interfaces for energy DePIN networks like Arkreen.
- Location Networks: Geo-anchored data services — FOAM and similar protocols for proof-of-location attestations, enabling applications that require cryptographic proofs of physical presence.
Application-Specific Chains (@aje/appchains)#
Rollup-as-a-service platforms enable projects to launch their own blockchain (with custom gas tokens, throughput, and features) at dramatically lower cost than an independent L1.
- Conduit, Caldera, and AltLayer: Managed rollup deployment services — configure chain parameters (stack, gas token, sequencer, data availability layer), deploy in minutes. Aje provides deployment configuration templates and integration patterns.
- OP Stack Configuration: Bedrock-based Optimism chains require op-geth (execution client) + op-node (consensus/rollup client) + several bridge contracts. Aje provides typed configuration objects for all deployment parameters.
- Arbitrum Orbit: Deploy an L3 (a rollup settling to Arbitrum rather than Ethereum) or an L2 (settling directly to Ethereum) using Arbitrum's technology. Orbit chains can use WASM or EVM execution environments.
- zkSync ZK Stack: Hyperchain deployment using zkSync's proving infrastructure — custom EVM-equivalent ZK rollups with shared liquidity pools through the Hyperbridge.
- Custom Precompiles: Application-specific precompiled contracts that execute at native speed (outside the EVM interpreter) for performance-critical operations — useful for ZK verification, cryptographic operations, and custom gas models.
Intent-Based Architecture (@aje/intents)#
Intent-based systems let users express what they want (swap X for Y, get the best price) rather than how to achieve it. Solver networks compete to find optimal execution.
- CoW Protocol (Coincidence of Wants): Batch auction settlement where the protocol finds "coincidences of wants" between multiple orders — if Alice wants to trade ETH for USDC and Bob wants USDC for ETH, they can trade directly without touching an AMM, saving both on price impact and gas. MEV protection through batch settlement.
- UniswapX: Off-chain signed orders filled by a permissionless filler network on-chain. Fillers compete to provide the best execution, paying for gas on behalf of the user (enabling gasless swaps) in exchange for a fee from the output.
- Across Protocol: Intent-based fast bridge — users express intent to move funds to another chain, relayers advance the funds immediately (within seconds), and the bridge protocol reimburses relayers after settlement.
- Intent Builder: Construct typed user intents with configurable constraints (minimum output amount, maximum slippage, deadline, acceptable chains, acceptable tokens) and submit to the appropriate solver network.
Liquid Restaking (@aje/restaking)#
Restaking allows staked ETH to simultaneously secure multiple protocols, earning additional yield for taking on additional slashing risk.
- EigenLayer: The foundational restaking protocol on Ethereum. ETH stakers can "restake" their staked ETH (or liquid staking tokens) into EigenLayer, delegating their economic security to Actively Validated Services (AVS) — new protocols that inherit Ethereum's security. Aje integrates restaking (ETH, stETH, rETH, cbETH), operator delegation, and AVS opt-in/opt-out.
- AVS Development Framework: EigenLayer AVSs are middleware systems secured by restaked ETH. Examples: data availability layers, cross-chain bridges, oracle networks, and rollup sequencers. Aje provides the interfaces for building and registering custom AVSs.
- Liquid Restaking Tokens (LRT): Protocols like EtherFi (eETH), Renzo (ezETH), Kelp DAO (rsETH), and Puffer Finance (pufETH) that restake deposited ETH into EigenLayer and issue a liquid token representing the position. The LRT accrues both Ethereum staking yield and EigenLayer restaking points.
- Restaking Strategy Management: Track restaking position across multiple EigenLayer operators, monitor slashing conditions for opted-in AVSs, and manage withdrawal queues (which have a delay for security).
Privacy Infrastructure (@aje/privacy)#
- Privacy Pools: Privacy-preserving transaction mixing with compliant withdrawal proofs — users can demonstrate their funds did not come from sanctioned sources (via association sets) without revealing their full transaction history. Vitalik Buterin's "Privacy Pools" proposal addresses the tension between privacy and regulatory compliance.
- FHE (Fully Homomorphic Encryption): Compute on encrypted data without decrypting it — the output is an encryption of the result. FHE enables private DeFi (trade without revealing your position size to front-runners), private governance voting (compute the tally without learning individual votes), and private ML inference. Current FHE is still 1,000–1,000,000× slower than plaintext computation but advancing rapidly.
- MPC (Multi-Party Computation) for Threshold Operations: General MPC protocols for threshold signing, private auctions, and distributed computation over private inputs — extending beyond just key management to general-purpose privacy-preserving computation.
- TEE (Trusted Execution Environment) Integration: Intel SGX and ARM TrustZone provide hardware-enforced isolated execution — code and data inside a TEE are protected even from the host operating system. Used for private order books, sealed-bid auctions, and confidential smart contracts.
On-Chain Gaming and Autonomous Worlds (@aje/gaming)#
On-chain gaming treats game state as blockchain-native data — world state is stored in smart contracts, game rules are enforced by on-chain logic, and players have true ownership of their in-game assets. Autonomous worlds extend this concept to open, permissionless environments that exist independently of any single developer.
- MUD Framework Integration: MUD (Multi-User Dungeon framework) is the leading framework for on-chain games on Ethereum. It provides a typed entity-component-system (ECS — a pattern where game objects are composed from reusable data components rather than inheritance hierarchies) that runs entirely in Solidity smart contracts. Aje integrates MUD's Store (on-chain database), World (contract registry), and Systems (authorised logic contracts) for building and extending on-chain games.
- World Engine Integration: World Engine is a horizontally scalable on-chain world framework that shards game state across multiple "Cardinal" game servers connected by cross-shard messaging. Aje provides World Engine deployment configuration, shard management, and cross-shard transaction routing — enabling on-chain worlds that scale beyond the throughput limits of a single smart contract.
- Game Asset Infrastructure: On-chain game asset management — ERC-1155 multi-token contracts for fungible resources and unique items, ERC-6551 token-bound accounts (NFT characters that own their own inventories), metadata standards for game asset interoperability across titles, and asset migration tooling for game upgrades.
- Game Economy Infrastructure: On-chain game economy primitives — fungible in-game currencies with configurable monetary policies (mint caps, burn mechanics, treasury splits), item crafting recipes enforced by smart contracts, market contracts (on-chain auction house, AMM-based in-game exchanges), and player-to-player trading with fee distribution.
- Autonomous World Patterns: Libraries for building open, permissionless virtual worlds where anyone can deploy extensions — world hooks (intercept and modify game actions), namespace registration (reserve a portion of the world's entity space), world extensions (add new systems to an existing world without deploying a new contract), and extension governance (on-chain voting on which extensions to accept into the canonical world).
- Gaming Layer 2 Integration: Specialised blockchain infrastructure for games — Immutable X (StarkWare-based ZK rollup for NFT-heavy games with zero gas fees for users), Ronin (Axie Infinity's dedicated sidechain, optimised for gaming transaction patterns), and Sky Mavis Ronin bridge patterns for moving assets between Ethereum and gaming chains.
Sui and Move Ecosystem (@aje/sui-move)#
The Move programming language was designed specifically for safe digital asset management — its type system prevents double-spending and asset duplication at the language level, making it inherently safer than Solidity for financial applications.
- Sui Network Client: Full Sui RPC client with typed interfaces for all Sui JSON-RPC methods — object queries (Sui's fundamental on-chain primitive is the object, not the account), transaction execution, event subscriptions, and checkpoint data. The Sui object model gives every on-chain entity a unique 32-byte ID and tracks precise ownership (owned by address, owned by another object, or shared), eliminating the accidental mutability that causes bugs in account-model blockchains.
- Move Language Utilities: Tools for working with Move-based smart contracts — package deployment and upgrade management, Move ABI (Binary Coded Serialisation — the Move equivalent of Ethereum ABI) encoding and decoding for function calls, and typed Move struct parsing for event processing. The BCS (Binary Canonical Serialisation) format used by Move is also provided as a standalone encoder/decoder for off-chain use.
- Sui DeFi Integrations: Native integrations with major Sui DeFi protocols — Cetus (the leading concentrated liquidity AMM on Sui, similar to Uniswap V3), DeepBook (Sui's native on-chain central limit order book), Scallop (lending protocol), and Turbos Finance (another concentrated liquidity AMM). All integrations follow Sui's sponsored transaction model, enabling platforms to pay gas on behalf of users.
- Aptos Support: Aptos is a sister chain to Sui — also using the Move language but with a different execution model (sequential transaction ordering rather than Sui's parallel execution via object ownership). Aje provides Aptos RPC client, Move module interaction, APT token management, and Aptos DeFi protocol integrations (LiquidSwap, PancakeSwap Aptos fork, Echelon lending).
- Programmable Transaction Blocks (PTBs): Sui's unique transaction model allows up to 1,024 commands in a single atomic transaction — each command's output can be used as the next command's input, enabling complex DeFi strategies (swap, deposit, stake, all in one transaction) without deploying custom smart contracts. Aje provides a typed PTB builder that prevents common misuse patterns.
Developer SDK (@aje/sdk)#
@aje/sdk is the public-facing composition layer that sits at the top of the
Aje dependency tree. Rather than requiring consumers to wire each individual
@aje/* package, @aje/sdk provides a single coherent entry point across five
sub-modules: core, react, python, cli, and docs.
- Core SDK Module: The
coresub-module provides a coherent developer surface over the Aje primitives — provider and signer wrappers, contract and transaction helpers, error normalisation, retry, event handling, factories, tree-shaking and bundling support, and compatibility shims. - React Module: The
reactsub-module ships an Aje context, wallet connectors, a React Query bridge, and hook factories —createUseAccount,createUseBalance,createUseContractRead,createUseContractWrite,createUseTransaction,createUseTokenBalance,createUseNFT, andcreateUseDeFi— each bound to a supplied Aje context. It also includes a wagmi-compatibility shim that mirrors wagmi's shape without depending on thewagmipackage, so it can be wired into a real wagmi setup at the application level. - CLI Module: The
clisub-module provides terminal tooling for wallet management, contract interaction, network queries, transaction handling, address-book management, and value decoding/formatting. - Python Module: The
pythonsub-module is a TypeScript code generator that emits Python bindings (PyO3/ctypes/cffi), Web3.py wrappers, Jupyter notebooks, and PyPI packaging metadata from TypeScript definitions. - Docs Module: The
docssub-module provides documentation-generation utilities for the SDK surface.
Multi-Chain RPC Client (@aje/rpc)#
@aje/rpc is a self-contained multi-chain JSON-RPC client with no runtime
dependencies — it is the only Aje package that declares neither peers nor
runtime dependencies. Its core is OshunRpcClient, which handles retry,
fallback, fan-out, and rate limiting across Ethereum, Bitcoin, Avalanche, and
Solana endpoints.
- Chain Providers: Ethereum, Bitcoin, Avalanche, and Solana providers
(
EthereumRpcProvider,BitcoinRpcProvider,AvalancheRpcProvider,SolanaRpcProvider). JSON-RPC 2.0 is used for Ethereum, Avalanche EVM, and Solana; the Bitcoin provider handles Bitcoin Core's JSON-RPC 1.0 dialect over HTTP basic auth. - Retry with Backoff: A configurable exponential-backoff
RetryPolicy(max retries, base/max delay, multiplier, jitter) that retries only the failure kinds inretryOn— by default network errors, rate limiting, and timeouts. - Fallback and Fan-Out: Ordered multi-endpoint fallback strategies and fan-out strategies, with per-endpoint health tracking and quorum support.
- Rate Limiting: Pluggable rate limiters (
createRateLimiter,NoopRateLimiter) to stay within provider request budgets. - Nonce Management: A
NonceManagerthat hands out leased nonces (NonceLease) for sequential transaction submission. - Gas Estimation: A
GasEstimatorfor EVM chains with per-call estimate options. - Confirmation Tracking: Chain-specific confirmation helpers —
waitForEthereumConfirmation,waitForBitcoinConfirmation,waitForSolanaConfirmation— with confirmation policies and depth lookups. - Typed Errors: A dedicated error hierarchy —
RpcExhaustedError,RpcMethodError,RpcNetworkError,RpcParseError,RpcQuorumError,RpcRateLimitError,RpcTimeoutError— for precise failure handling.
Concordia Settlement and Escrow (@aje/settlement-escrow)#
@aje/settlement-escrow is a narrow integration point between the Aje and
Concordia domains. Concordia owns the bargaining and review flow — the legal
lifecycle of a contract clause — while Aje owns the settlement plan and
chain-specific execution detail. This boundary exists because the two concerns
require very different expertise: Concordia handles clause semantics and dispute
logic; Aje handles blockchain mechanics. The package (Phase 179.7.2.4) is
implemented and maps a Concordia escrow_release clause to a chain-ready Aje
escrow deployment plan.
- Deployment Planning:
planDeployment()takes a validated Concordia escrow-release payload — case ID, clause ID, target chain, token reference and decimals, principal amount, escrow contract reference, and a list of milestones — and produces a validatedEscrowDeploymentPlan. - Milestone Allocation: Each milestone's release amount is allocated from
its
releaseFractionusing integer math at a 1,000,000 scale; the final milestone absorbs any rounding dust so the milestone amounts sum exactly to the principal. - Plan Validation: The Zod
EscrowDeploymentPlanSchemarejects any plan whose milestone fractions do not sum to 1, or whose milestone amounts do not sum to the principal. - Supported Chains:
ethereum,polygon,arbitrum,optimism,base,starknet,aptos,sui,solana,near,cosmos,bitcoin, and atenant_private_chainoption. - Release Oracles: Each milestone names an oracle source —
mediator_attestation,dual_party_attestation,oracle_chainlink,oracle_uma,court_order,kleros_arbitration, ortenant_admin. - Arbitration Backstop: Each plan declares an arbitration backstop —
kleros,uma_optimistic,court_order,platform_arbitrator,tenant_reviewer, ornone— and may carry a challenge window and a0x-prefixed agreement hash anchored on-chain at deposit time. - Next-Milestone Lookup:
nextMilestoneAfter()returns the next unreleased milestone in due-date order.
Concordia owns the bargaining and review flow; Aje owns the settlement plan and chain-specific execution detail.
Engine Monetization Rails (Phase 164, planned)#
Aje is a co-owner of the Neith engine monetization and LiveOps stack (Phase 164,
@neith/liveops-*): where the engine store settles creator payouts, distributes
royalties, or accepts crypto/stablecoin payment, Aje supplies the on-chain rails
— payment-splitter and ERC-2981-style royalty distribution, stablecoin
settlement, and payout escrow — while Neith owns the in-engine economy, IAP, and
storefront. The boundary mirrors the Concordia settlement integration above:
Neith owns the commerce semantics, Aje owns the blockchain mechanics.
(planned)