# Architecture Source: https://docs.capx.ai/capx-chain/core-concepts/architecture Capx Chain's architecture is layered to optimize for security, scalability, and developer experience, leveraging the strengths of the Arbitrum Nitro stack. Arbitrum Nitro is a technology stack that powers Arbitrum's Layer 2 (L2) scaling solutions for Ethereum. It's designed to provide faster and cheaper transactions while leveraging Ethereum's security. Capx-Chain-Architectureitecture Capx-Chain-Architectureitecture Capx Chain operates as an optimistic rollup. This means it "optimistically" assumes all transactions are valid and processes them off-chain on its Layer 2. It then periodically submits batches of these transactions (as compressed calldata) to the Ethereum Layer 1 (L1) for final settlement. If a fraudulent transaction is suspected, a dispute resolution process (fraud proof) is initiated. Nitro features interactive fraud proofs, which are designed to be more efficient by re-executing only the disputed part of a transaction. ## Key Architectural Layers & Components ### **1. Ethereum Layer 1 (The Foundation)** * **Consensus Layer (Leveraged by Capx):** Capx Chain relies on the underlying Ethereum blockchain for its security and finality. It doesn't have its own separate consensus mechanism for L2 state in the same way a Layer 1 blockchain does. Instead, the validity of Capx Chain's state is ultimately guaranteed by the ability to prove it on Ethereum L1. * **Capx L1 Smart Contracts:** These are crucial contracts deployed on Ethereum that manage the rollup protocol. Key contracts include: * **Inbox Contract (SequencerInbox):** This contract receives batches of ordered and compressed transactions from the L2 Sequencer. * **Outbox Contract:** Facilitates communication and asset transfers from Capx Chain L2 back to Ethereum L1. * **Rollup Core Contracts (e.g., RollupCore.sol):** Manage the state of the rollup, track assertions made by validators about the L2 state, and facilitate the fraud proof mechanism. * **Bridge Contracts:** Enable the transfer of assets (ETH and ERC-20 tokens) between Ethereum L1 and Capx Chain L2. ### **2. Capx Chain Layer 2 (The Scaling Engine)** #### **Networking Layer (L2):** * **Sequencer:** This is a key component in Capx Chain. The Sequencer orders transactions, compresses them, and posts these batches as calldata to the Ethereum L1 Inbox contract. It provides users with fast, "soft" finality (confirmation within 1-2 seconds). * **Validators/Full Nodes (L2):** These nodes execute all L2 transactions and can challenge the Sequencer's assertions if they detect an incorrect state transition. They play a crucial role in security by observing the chain and initiating fraud proofs if necessary. * **RPC Endpoints:** Allow users and dApps to interact with the Capx Chain network (submit transactions, query state, etc.). #### **Execution Layer (L2):** This is where smart contracts are executed on Capx Chain. * **Arbitrum Virtual Machine (AVM) - Powered by Nitro:** Nitro significantly upgraded Arbitrum's execution environment. A key innovation is compiling the core of Geth (Go Ethereum, the most popular Ethereum client) directly into Arbitrum. This provides high EVM compatibility, meaning most Ethereum smart contracts can run on Capx Chain with minimal to no changes. * **WASM (WebAssembly):** Nitro utilizes WASM for its fraud proofs. The L2 Capx Chain engine can be written and compiled using standard languages, and for fraud proofs, the relevant code (specifically the State Transition Function) is compiled to WASM. This separation of execution (native code for speed) and proving (WASM for verifiability and portability) is a core design principle. * **ArbOS:** This is a custom operating system for the L2 chain. It handles L2-specific functionalities such as calldata decompression, gas fee management, cross-chain communication between L1 and L2, and managing smart contract lifecycles. The Nitro version of ArbOS was rewritten in Go. * **State Transition Function (STF):** This deterministic function defines how the state of the L2 chain changes in response to transactions. It's compiled into native machine code for fast execution by Nitro nodes and into WASM for fraud proofs. * **Stylus:** An upgrade that allows developers to write smart contracts in languages like Rust and C++ that compile to WASM, in addition to Solidity for the EVM. These WASM contracts can interoperate with EVM contracts. #### **Data Availability (DA) Layer Strategy:** * **The Role of Data Availability:** For an optimistic rollup like Capx Chain, ensuring data availability is paramount. It means that all the data required to reconstruct the L2 state and verify transactions must be accessible to anyone. This allows validators to check for fraud and users to exit the L2 even if the Sequencer becomes malicious or unavailable. * **Capx Chain's Approach to DA:** Capx Chain, leveraging the flexibility of the Arbitrum Nitro stack, has the capability to integrate with alternative Data Availability solutions. This can include options like an AnyTrust model using a Data Availability Committee (DAC) for significantly lower costs, or dedicated third-party DA layers (e.g., Celestia, EigenDA, Avail) which offer different trade-offs in terms of cost, throughput, and security assumptions. * **Impact on Users & Developers:** The choice of DA layer directly impacts transaction costs on Capx Chain. Using Ethereum L1 is typically more expensive but offers stronger security guarantees. Alternative DA solutions aim to reduce these costs, potentially enabling new types of applications, but may involve different trust assumptions (e.g., trusting a DAC in an AnyTrust model). #### **Key Built-in Contracts/Modules (L2):** * **Token Bridging Contracts (L2 Side):** Work in conjunction with the L1 bridge contracts to facilitate asset movement. ### **Interactions & Flows:** 1. **Transaction Submission:** Users submit transactions to an Capx Chain L2 node (often the Sequencer). 2. **Sequencing & Batching:** The Sequencer orders transactions, compresses them, and posts a batch to the L1 Inbox contract. 3. **L2 Execution:** Capx Chain nodes execute the transactions using the Nitro runtime (Geth core + ArbOS). 4. **State Assertion:** Validators (or the Sequencer acting as an asserter) post assertions about the new L2 state to the L1 Rollup Core contracts. 5. **Challenge Period & Fraud Proofs:** There's a period during which any validator can challenge an assertion if they believe it's incorrect. If challenged, an interactive fraud proof process occurs, re-executing disputed parts in WASM on L1 to determine the correct outcome. 6. **Finality on L1:** Once a state assertion is confirmed on L1 (either unchallenged after the dispute period or successfully defended through a fraud proof), it's considered final. 7. **Withdrawals (L2 to L1):** Users initiate withdrawals on L2, which are then processed through the Outbox contract on L1 after a delay period (to allow for fraud proofs). # Consensus Mechanism Source: https://docs.capx.ai/capx-chain/core-concepts/consensus Capx Chain, utilizing the Arbitrum Nitro stack, achieves consensus through an optimistic rollup mechanism. This means L2 (Capx Chain) transactions are executed and batched with the optimistic assumption of validity for speed and low cost. True finality and security are derived from the underlying L1 (Ethereum) through a system of state assertions and fraud proofs. Capx Chain Consensus Capx Chain Consensus (L2: Capx Chain Execution & Proposal)

1. `User ---sends L2 Tx---> [Capx Chain Sequencer]` 2. `[Sequencer]` * Orders transactions. * Executes transactions, computes new L2 state. * Creates a `[Transaction Batch]` and a new `[L2 State Root_S]`. * Provides `---Soft Confirmation---> User`. 3. `[Sequencer] ---submits Tx Batch (calldata)---> [L1 Ethereum: Inbox Contract]` * *Data is now anchored on L1, ensuring Data Availability.*

(L1: Assertion & Challenge Period)

4. `[Asserter (e.g., Sequencer)] ---posts Assertion(L2 State Root_S)---> [L1 Ethereum: Rollup Core Contract]` 5. `[Rollup Core Contract] ---initiates Challenge Period (e.g., 7 days)---` * *During this period, any validator can challenge the assertion.* * *Validators can independently verify the state root by executing the transactions in the batch.* * *The challenge period allows for a dispute resolution process if discrepancies arise.*

(L2 & L1: Validation & Potential Challenge)

6. `[Capx Chain Validators (L2 Full Nodes)]`: * Fetch `[Transaction Batch]` from L1 Inbox. * Independently execute transactions, compute their own `[L2 State Root_V]`. * Compare `[L2 State Root_V]` with asserted `[L2 State Root_S]` on L1. 7. **Decision Point during Challenge Period:** * **IF `State Root_V == State Root_S` (Happy Path):** * Validators take no action against this assertion. * `IF Challenge Period Ends without successful challenge:` * `[L1 Ethereum: Rollup Core Contract] ---confirms Assertion---> [L2 State Root_S is Finalized]` ✅ * **This is L1-Secured Finality for the L2 Block.** * **IF `State Root_V != State Root_S` (Dispute Path):** * `[A Challenging Validator] ---initiates Fraud Proof against Assertion(L2 State Root_S)---> [L1 Ethereum: Rollup Core Contract]` * **Fraud Proof Process (Interactive Bisection in Nitro):** * The contract facilitates an interactive game between the Asserter and Challenger. * They narrow down the dispute to a single differing instruction in the L2 execution. * This single instruction is then executed via a WASM module on L1 (the `OneStepProof` mechanism) to determine the correct state transition. * `IF Challenger Wins:` Fraudulent assertion is rejected, Challenger is rewarded, Asserter is penalized. The correct state can be asserted. * `IF Asserter Wins:` Challenge is dismissed, Challenger may lose their stake. Assertion proceeds towards finalization.

### **Key Components & Roles in Consensus:** 1. **Sequencer (L2):** * **Role:** A designated node (or a decentralized set of nodes in future iterations of Arbitrum technology) responsible for accepting user transactions, determining their order, executing them, and bundling them into compressed batches. * **Block Proposal (L2):** The Sequencer effectively proposes L2 "blocks" or batches by creating an ordered sequence of transactions and calculating the resulting state transition. This provides users with fast, sub-second "soft" confirmations or pre-confirmations. * **L1 Interaction:** Submits these transaction batches as `calldata` to an `Inbox` contract on Ethereum L1. This ensures data availability. 2. **Asserters (Typically includes the Sequencer, can be other permissioned L2 Nodes):** * **Role:** After L2 blocks are processed and data is posted to L1, an Asserter posts a cryptographic commitment (a state root) of Capx Chain's new state to the `Rollup Core` contract on Ethereum L1. This is an "assertion" about the outcome of executing a specific batch of L2 transactions. * **State Finalization (Path to):** These assertions initiate a challenge period on L1. 3. **Validators (Full L2 Nodes):** * **Role:** These nodes independently execute all L2 transactions from the data available on the L1 `Inbox`. They compute their own version of the L2 state root. * **Verification:** They compare their calculated state root against the state root asserted on L1 by the Asserter. * **Challenge Initiation:** If a Validator detects a discrepancy (i.e., the asserted state root is incorrect according to their computation), they can initiate a fraud proof challenge on L1 during the challenge period. 4. **Ethereum L1 Contracts (e.g., `Rollup Core`, `Inbox`, `Bridge`):** * **Role:** These smart contracts on Ethereum are the arbiters of truth for Capx Chain. * `Inbox`: Receives transaction data from the Sequencer. * `Rollup Core`: Manages the state of the rollup, tracks assertions, and facilitates the fraud proof mechanism. * **Finality:** L1 provides the ultimate settlement and finality. An L2 state root is considered final once its assertion has survived the challenge period on L1, or a fraud proof has successfully defended it (or corrected a fraudulent one). # The Token Factory & Registry: Standardizing AI Assetization Source: https://docs.capx.ai/capx-chain/core-concepts/token-registry The Capx ecosystem pioneers the transformation of AI apps into verifiable, tradable digital assets. This is achieved through a meticulously designed **Token Factory** protocol and an accompanying **Token Registry**, both operating immutably on Capx Chain. This system provides a standardized, transparent, and automated framework for endowing every deployed AI apps with its own distinct on-chain economic identity. ## The ERC-20 Standard for AI Apps: Design Philosophy The decision to pair every AI app with a dedicated **ERC-20 fungible token** is a deliberate architectural choice, predicated on several core tenets: * **Intrinsic Economic Representation:** Each token serves as a direct, quantifiable representation of an apps potential utility, governance rights, or claim on its generated value. This moves AI beyond a service model to an asset model. * **Standardized Fungibility & Composability:** Adherence to the ERC-20 standard ensures seamless integration with the broader DeFi ecosystem on Capx Chain (and potentially beyond), allowing app tokens to be used in lending protocols, as collateral, or within other financial primitives. * **Predictable Economic Framework:** A uniform issuance model provides a stable foundation for valuation, market analysis, and the development of sophisticated financial instruments around AI apps. ## The Token Factory: Protocol Mechanics & Automated Issuance The Capx Token Factory is a non-upgradeable smart contract system on Capx Chain responsible for the genesis of all AI app tokens. Its operation is deeply integrated with the AI app deployment pipeline originating from Capx Cloud. ### **Contract Implementation:** `Capx Agent Contracts` [➹](https://github.com/Capx-AI/Capx-Super-App-Contracts/tree/prod-deployment/agents_units-to-coins/contracts) ```solidity theme={null} //SPDX-License-Identifier: MIT pragma solidity ^0.8.20; interface ICapxAgentFactory { struct CapxAgentParams { string name; string symbol; string tokenURI; uint8 decimals; uint256 ecr20TotalSupply; address agentOwner; } struct CapxAgentInfo { uint256 id; address agent; string name; string symbol; string tokenURI; uint8 decimals; uint256 ecr20TotalSupply; address initialAgentOwner; } event NewCapxAgent( address indexed agent, address indexed owner, string name, string symbol, string tokenURI, uint8 decimals, uint256 erc20TotalSupply ); function createAgent(CapxAgentParams memory _agentParams) external; function name() public view returns (string memory); function symbol() public view returns (string memory); function decimals() public view returns (uint8); } ``` ### **Technical Issuance Process:** 1. **Agent Deployment Trigger:** Upon successful deployment of an AI app via Capx Cloud, a secure call is made to the Token Factory contract on Capx Chain. 2. **Dedicated Agent Wallet Context:** The deployment process ensures the app is associated with a Privy-linked wallet. This wallet becomes the initial recipient or controller of certain token allocations, ensuring secure, programmatic control for the app or its creator. 3. **Immutable Token Contract Generation:** The Token Factory executes the `createAgent` function (or a similar internal method). This function deploys a new, distinct ERC-20 compliant smart contract for the app. * **Fixed Supply Parameter:** `1,000,000,000` (one billion) tokens are minted to a `totalSupply` variable within the new token contract. This supply is **immutable**; the ERC-20 contract itself will contain no `mint()` or `burn()` functions callable post-deployment, ensuring absolute supply predictability. * **Standardized Token Parameters:** * **`name():`** Derived from the agent's registered name (e.g., "Agent X Token"). * **`symbol():`** A unique ticker (e.g., "AXT"). * **`decimals():`** Standard ERC-20 decimal places (typically 18). * **Ownership & Control:** The Token Factory may temporarily hold ownership to set initial parameters or immediately transfer ownership of the new token contract to the app's Privy-linked wallet or a pre-specified developer/DAO address. 4. **Automated Initial Allocation & Vesting (Conceptual):** * A significant portion of the `totalSupply` is programmatically transferred to predefined addresses or vesting contracts. This distribution is determined by allocation rules. * **Developer/Creator Allocation:** Transferred to the developer's wallet, potentially via a vesting contract (e.g., linear release over time) to align long-term incentives. * **Ecosystem/Treasury Reserve:** Allocated to a Capx-controlled multisig or DAO treasury for grants, community incentives, or strategic airdrops. * **Initial Liquidity Pool Seeding Allocation:** A portion designated to bootstrap the app's trading pair on the native Capx DEX. * **Public Float:** The remaining tokens become immediately available for circulation. * *Future Iterations:* The allocation logic within the Token Factory or associated contracts may incorporate more complex vesting schedules or DAO-configurable parameters, subject to on-chain governance. ## The Capx Token Registry: On-Chain Verifiability & Discovery Complementing the Token Factory is the **Capx Token Registry**. This registry serves as the canonical, on-chain directory of all legitimate AI app tokens within the ecosystem. ### **Registry Functions & Importance:** * `registerToken(address agentTokenContract, bytes32 agentIdentifier):` When the Token Factory creates a new app token, it (or an authorized address) calls this function to log the new token contract's address alongside a unique identifier for the AI app (e.g., a hash of its metadata or deployment ID). * **Source of Truth:** The registry provides an immutable, auditable record, allowing dApps, explorers, and users (via the Capx SuperApp) to verify that a given ERC-20 token is an officially sanctioned Capx AI app token, mitigating risks of counterfeit or imposter tokens. * **Metadata Linkage:** The registry might store or link to off-chain (e.g., IPFS) or on-chain metadata about the app (description, creator, performance metrics pointers), enabling rich data display in frontends. * **Facilitating Discovery & Integration:** The Capx SuperApp and the native DEX directly query this registry to populate lists of tradable apps, ensuring users only interact with verified assets. Third-party services can also integrate with this registry for data provisioning. ### **Lifecycle & Governance:** 1. **Deployment & Automatic Registration:** An AI agent app is deployed via Capx Cloud; the Token Factory mints its 1 billion tokens and registers the new token contract with the Capx Token Registry. 2. **Initial Liquidity Event:** A portion of the minted tokens, paired with \$CAPX, is used to seed a liquidity pool on the Capx DEX, establishing an initial market. 3. **Market Dynamics:** Users discover the app token via the Capx SuperApp (which sources data from the Registry and DEX), trade it, stake it (if yield mechanisms are enabled), and participate in its micro-economy. 4. **Value Accrual & Fluctuation:** The app token's market value evolves based on the app's utility, performance, adoption, demand, and overall market sentiment, all transparently reflected on-chain. *** # The DEX & Liquidity Engine: Powering On-Chain AI App Markets Source: https://docs.capx.ai/capx-chain/core-concepts/trading-engine For tokenized AI apps to become a truly liquid asset class, a dedicated, efficient, and deeply integrated trading infrastructure is indispensable. The Capx ecosystem provides this through its native **Decentralized Exchange (DEX) & Liquidity Engine**, a purpose-built automated market maker (AMM) operating directly on Capx Chain. This AMM is an optimized fork of the battle-tested **Uniswap V2 protocol**, tailored to the specific requirements of the AI app token economy. ### Architectural Foundation: Uniswap V2 Core Principles Leveraging Uniswap V2 as the foundational codebase provides immediate access to its proven strengths: * **`Constant Product Formula (x * y = k):`** The core AMM logic ensures deterministic pricing based on the ratio of reserves in a liquidity pool. * **Permissionless Liquidity Provision:** Enables any user to contribute assets to liquidity pools and earn a proportional share of trading fees. * **Decentralized & Non-Custodial Trading:** Users retain full custody of their assets throughout the trading process, interacting directly with smart contracts. * **Robustness & Security:** Benefits from the extensive auditing and real-world resilience demonstrated by Uniswap V2. However, the Capx DEX is not a generic fork; it incorporates specific design choices optimized for the AI app token lifecycle. ## Uniswap V2 Core Interfaces Before delving into Capx-specific extensions, here are the canonical Uniswap V2 interfaces that underpin all AMM operations. ### Factory Contract Interface ```solidity theme={null} interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } ``` *`Governance of pool registry and protocol-fees; deploys new pair via createPair(tokenA, tokenB).`* ### Pair Contract Interface ```solidity theme={null} interface IUniswapV2Pair { event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; } ``` *`Core pool mechanics: mint(), burn(), swap(), sync(), and reserve queries.`* ### Router Contracts ```solidity theme={null} // Core swap + liquidity (Router01) function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); // Permit-enabled + fee-on-transfer variants (Router02) function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; ``` *User-facing entry points: multi-hop swaps, liquidity management, permit and fee-on-transfer support.* ### Library Helpers ```solidity theme={null} function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts); function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts); ``` *On-chain price/amount calculations by reading pair reserves along a path.* ## Strategic Optimizations for the AI App Economy 1. **Universal Base Pair: \$CAPX:** * **Liquidity Concentration:** All AI app tokens are exclusively paired against the Capx ecosystem's native utility token, \*\*$CAPX** (e.g., `AgentTokenA/$CAPX`, `AgentTokenB/\$CAPX\`). This contrasts with general-purpose DEXs that allow arbitrary pairings. * **Benefits:** * **Simplified UX:** Users only need to hold \$CAPX to interact with any AI App token market. * **Improved Price Stability:** Concentrating liquidity against a common base asset generally leads to deeper markets and reduced slippage for app tokens, especially for newly launched apps. * **Efficient Routing:** Simplifies multi-hop swap calculations if ever needed, though direct \$CAPX pairs are the primary design. * **Strengthened CAPX Utility:** Enhances the demand and utility of the \$CAPX token as the primary gateway to the AI App economy. 2. **Isolated Liquidity Pools per App:** * Each AI app token, upon creation and registration, has the capability to have its own dedicated `AgentTokenX/$CAPX` liquidity pool contract deployed. * This isolation prevents a "rug pull" in one app's pool from directly impacting the liquidity or integrity of another app's distinct pool, though systemic risks via \$CAPX volatility remain a general market factor. 3. **Gas Efficiency on Capx Chain (L2):** * Operating on Capx Chain (an L2 leveraging Arbitrum Nitro) inherently means Uniswap V2 operations (swaps, liquidity additions/removals) are significantly cheaper and faster than on Ethereum L1. This is crucial for fostering active trading of potentially lower-value or early-stage app tokens. 4. **Deep SuperApp Integration:** * The Capx SuperApp provides a seamless front-end for interacting with the DEX. Users can swap tokens, view pool statistics, and (in future phases) manage liquidity positions directly within the AI App's profile or a dedicated DEX interface in the app, abstracting away direct smart contract interactions for most users. ## Core DEX Operations & Smart Contracts * **Factory Contract (Uniswap V2 Factory):** * Responsible for deploying new unique `AgentTokenX/$CAPX` pair contracts (liquidity pools). * Maintains a registry of all created pairs. * Only permits pair creation with \$CAPX as one of the assets and a verified agent token (from the Capx Token Registry) as the other. * **Pair Contracts (Uniswap V2 Pair):** * Each `AgentTokenX/$CAPX` pool is its own smart contract. * Holds reserves of the two tokens. * Implements the `swap()`, `mint()` (for adding liquidity), and `burn()` (for removing liquidity) functions. * Emits `Sync` and `Swap` events crucial for off-chain price tracking and analytics. * **Router Contract (Uniswap V2 Router):** * Provides user-friendly functions to interact with pair contracts (e.g., `swapExactTokensForTokens`, `addLiquidity`). * Handles the necessary token transfers and calculations, abstracting complexity from the end-user or dApp integrator. * Enforces deadlines and slippage protection parameters for swaps. ### **The Swap Execution Flow (Simplified):** 1. **User Initiates Swap (via SuperApp):** User intends to swap `amountIn` of \$CAPX for `AgentTokenX`. 2. **Router Interaction:** SuperApp crafts a transaction calling a function like `swapExactCAPXForTokens(amountIn, amountOutMin, path, to, deadline)` on the Capx DEX Router contract. * `path`: Will be `[$CAPX_address, $AgentTokenX_address]`. 3. **Token Transfer & Pair Call:** The Router pulls `amountIn` of CAPX from the user, then calls the `swap()` function on the specific `AgentTokenX/$CAPX` pair contract. 4. **Pair Contract Logic:** * The pair contract calculates the `amountOut` of `AgentTokenX` based on current reserves and the constant product formula, accounting for a 0.3% trading fee (standard Uniswap V2, potentially configurable for Capx). * It transfers `amountOut` of `AgentTokenX` to the user and updates its internal reserves. * Emits `Swap` and `Sync` events. 5. **Transaction Finality:** The L2 transaction is confirmed rapidly on Capx Chain. ## Liquidity Provision & Incentives (Roadmap) While initial liquidity may be seeded programmatically or by developers/Capx Treasury, the long-term health of the AI App token markets will depend on community liquidity provision. * **Current State:** Users can trade. LP management features are typically rolled out progressively. * **Future LP Features:** * **SuperApp LP Interface:** Tools within the SuperApp to add/remove liquidity to `AgentTokenX/$CAPX` pairs. * **LP Token (ERC-20):** When users add liquidity, they receive LP tokens representing their proportional share of the pool. These LP tokens can themselves be staked or used in other DeFi protocols. * **Fee Accrual:** LPs earn 0.3% (or the configured percentage) of all trading volume in their respective pools, proportional to their share. * **Advanced Analytics:** Dashboards displaying LP PnL, impermanent loss estimations, fee generation, and share of pool. * **Protocol-Level Incentives:** Potential for distributing additional \$CAPX rewards or other incentives to LPs in strategic app token pools to bootstrap liquidity (often referred to as "liquidity mining"). ## Security & On-Chain Oracle Potential * **Audited Base & Controlled Modifications:** The security heavily relies on the proven Uniswap V2 contracts, with any Capx-specific modifications undergoing rigorous auditing. * **Token Whitelisting via Registry:** The DEX interacts only with App tokens verified by the Capx Token Registry, minimizing the risk of scam tokens in native pools. * **On-Chain Price Feeds (TWAP Oracles):** Uniswap V2 pair contracts can serve as on-chain price oracles by providing time-weighted average prices (TWAPs). This allows other smart contracts on Capx Chain to securely query the recent historical price of an AI App token against \$CAPX, enabling more advanced financial applications and App logic based on token value. # Getting Started Source: https://docs.capx.ai/capx-chain/getting-started Interacting with Capx Chain is straightforward. Here’s how you can get set up: ### Setting up a Wallet To interact with Capx Chain, you'll need an EVM-compatible wallet like MetaMask, Rabby, or Trust Wallet. Here are the general steps to add Capx Chain as a custom network: 1. **Open Your Wallet:** Access your browser extension or mobile wallet application. 2. **Navigate to Network Settings:** Look for an option like "Add Network," "Custom RPC," or "Networks." 3. **Enter Capx Chain Details:** You will need to provide the following information (exact values for Testnet and Mainnet will be provided here): | Setting | Value | | ---------------------- | ---------------------- | | **Network Name** | `Capx Mainnet` | | **RPC URL** | `https://rpc.capx.ai` | | **WSS URL** | `wss://rpc.capx.ai` | | **Chain ID** | `757` | | **Currency Symbol** | `CAPX` | | **Block Explorer URL** | `https://capxscan.com` | 4. **Save the Network:** After filling in the details, save the network. You should now be able to select Capx Chain from your list of networks. ### Acquiring Tokens (CAPX) * **Testnet:** * A faucet will be available for developers and users to obtain Testnet CAPX tokens for experimentation. * **Faucet URL:** `https://faucet.testnet.capx.ai/` [➹](https://faucet.testnet.capx.ai/) * **Mainnet:** * Information on how to acquire Mainnet CAPX tokens (e.g., through exchanges, bridges from L1) will be available here upon the Mainnet launch. ### Making Your First Transaction Once your wallet is set up and funded with CAPX tokens: 1. **Ensure Capx Chain is Selected:** Double-check that your wallet is connected to the correct Capx Chain network (Testnet or Mainnet). 2. **Initiate a Transfer:** * Click "Send" or "Transfer" in your wallet. * Enter the recipient's Capx Chain address. * Enter the amount of CAPX/GAS you wish to send. * Review the transaction details and estimated gas fee. * Confirm the transaction. 3. **Check Transaction Status:** You can copy the transaction hash (ID) provided by your wallet and paste it into the Capx Chain Block Explorer to view its status and details. # Capx Chain: The Backbone of Capx AI Source: https://docs.capx.ai/capx-chain/introduction ## Why Capx Chain? The growing field of AI apps and their integration into blockchain ecosystems presents unique technical requirements. Existing general-purpose blockchains can face limitations in handling the specific demands of scalability, transaction costs, and specialized tooling needed for an efficient AI app marketplace. Capx Chain is designed as a specialized infrastructure to directly address these needs, providing a dedicated and optimized environment for the development, management, and interaction of tokenized AI apps within the Capx ecosystem. ## Vision & Goals The vision for Capx Chain is to be the premier blockchain platform for the tokenization, interaction, and governance of AI apps, fostering a transparent, efficient, and community-driven AI economy. Its primary goals are to: * **Empower AI App Tokenization:** Establish a robust and standardized framework for representing AI apps as versatile digital assets (ERC20s) that can encapsulate identity, provenance, fractional ownership, access rights, and governance participation. * **Facilitate On-Chain AI Interactions:** Create a secure and verifiable environment for all interactions involving AI apps, users, and smart contracts, ensuring transparency and auditability for AI-driven economic activities. * **Enable Decentralized AI Governance:** Provide the infrastructure for community-led governance models, allowing stakeholders to collectively shape the development and operational parameters of AI apps and the broader Capx ecosystem. * **Deliver Scalable & Cost-Effective Operations:** Ensure the underlying infrastructure can support a high volume of transactions and complex computations anticipated in a thriving AI app marketplace, quickly and at minimal cost. * **Guarantee Secure Asset Lifecycle Management:** Offer a highly secure and resilient platform for the entire lifecycle of AI-related digital assets, from their creation and trading to their ongoing management and evolution. ## Key Benefits of Capx Chain Capx Chain integrates cutting-edge blockchain technologies to deliver a superior platform tailored for AI: * **Exceptional Scalability & Speed (Arbitrum Nitro):** Built upon the Arbitrum Nitro stack, Capx Chain is capable of processing thousands of transactions per second. This high throughput ensures a fluid and responsive user experience, critical for real-time AI interactions and active markets. * **Drastically Reduced Transaction Costs (L2 with Celestia DA):** As a Layer 2 solution that innovatively leverages Celestia for Data Availability, Capx Chain slashes transaction fees to a fraction of L1 costs. This makes micro-transactions, frequent apps interactions, and complex on-chain AI logic economically feasible. * **Uncompromised Security (Ethereum L1 & EigenLayer Sequencing):** Capx Chain inherits the formidable, battle-tested security of the Ethereum mainnet for ultimate settlement and dispute resolution. This is further augmented by utilizing EigenLayer's restaking mechanisms to secure and decentralize its sequencing operations, adding robust layers of protection. * **Multi-Language Smart Contract Support (EVM & WASM via Arbitrum Stylus):** Uniquely, Capx Chain supports smart contracts written in Solidity (targeting the EVM) and also languages like Rust, C, and C++ (which compile to WASM via Arbitrum Stylus). This flexibility opens up development to a significantly broader pool of programmers and enables more computationally intensive AI logic to be executed efficiently on-chain. * **Future-Proof Modular Architecture (Arbitrum Orbit & Celestia):** By leveraging the modularity of the Arbitrum Orbit stack for its L2 framework and Celestia for data availability, Capx Chain is designed for enhanced flexibility, easier upgrades, and the ability to independently scale or customize different components of the chain as the ecosystem evolves. * **Robust Decentralized Sequencing (Symbiotic):** Capx Chain employs Symbiotic's restaking mechanisms to establish a decentralized and resilient set of sequencers. This critical design choice mitigates risks associated with single points of failure or censorship, ensuring high liveness and integrity for transaction ordering. * **AI-Centric Infrastructure & Tooling:** The chain is not just a generic L2; it is conceived with the unique lifecycle of AI apps in mind. This includes considerations for pre-deployed smart contract factories, standardized interfaces for app tokenization, and on-chain registries designed to streamline the development and management of AI app as digital assets. # Attestor Nodes Source: https://docs.capx.ai/capx-cloud/core-concepts/attestor Attestor Nodes serve as the Capx Cloud’s quality assurance mechanism, validating tasks executed by Performer Nodes. Their primary objective is to ensure that all computations meet the network’s predefined standards for accuracy and reliability. This process strengthens trust and prevents tampering or dishonesty within the network. **Key Responsibilities:** * **Validation Process:** Upon receiving the Proof of Task and associated results from a Performer Node, Attestor Nodes independently verify the accuracy and legitimacy of the execution. * **Consensus Mechanism:** Attestor Nodes participate in a consensus protocol, where they cast votes on the validity of each task. A task is approved if a supermajority (typically two-thirds) of Attestor Nodes confirm its validity. * **Enforcement of Penalties:** If a significant portion of Attestor Nodes (e.g., more than one-third) deems a task invalid, the network enforces penalties, such as slashing, against the responsible Performer Node to uphold network integrity. **Importance in the Network:** By validating tasks, Attestor Nodes ensure that only accurate and trustworthy computations are accepted, preventing fraudulent or erroneous outputs. Their role is essential for maintaining the network's credibility and ensuring that users can trust the results produced by the Capx Cloud. # Delegators Source: https://docs.capx.ai/capx-cloud/core-concepts/delegator Delegators are crucial contributors to the Capx Cloud’s security and stability. They delegate their staked assets to trusted operators, thereby supporting network infrastructure while earning rewards for their participation. Delegators play a vital role in decentralizing the network by distributing stake among various operators. **Key Responsibilities:** * **Operator Selection:** Delegators carefully choose reputable Operators based on performance metrics, reliability, and trustworthiness. * **Stake Delegation:** They allocate their assets to selected Operators, thereby enhancing the Operators' capacity to manage more tasks and secure the network. * **Governance Participation:** Delegators engage in voting processes, influencing decisions on network policies, upgrades, and other governance matters. **Importance in the Network:** Delegation lowers the barrier to entry for those who wish to support decentralized infrastructure without managing technical operations. Through their contributions, Delegators enhance the network’s economic security, allowing it to scale while maintaining decentralization and resilience. # Capx Cloud Infrastructure Source: https://docs.capx.ai/capx-cloud/core-concepts/infrastructure Capx Cloud Infrastructure Capx Cloud Infrastructure ## Component Overview ### 1. User The individual or team responsible for initiating development by providing or generating source code and interacting with the platform to deploy, test, and iterate on agentic systems. ### 2. AI Generated Code / Custom Code The foundational logic used to create and define Services, MCP Servers, and AI Agents, encompassing both custom-written and AI-generated implementations. ### 3. Services General-purpose modules such as APIs, user interfaces, backend logic, data processors, scrapers, indexers, inference wrappers, or cryptographic tools. These provide reusable, foundational functionalities utilized independently or by MCP Servers and AI Agents. ### 4. MCP Servers (Model Context Protocol Servers) Lightweight programs that expose specific capabilities through the standardized Model Context Protocol. They act as gateways to data sources, handling authentication, data retrieval, and formatting, enabling AI applications to access external data in a standardized manner . ### 5. AI Agents Autonomous, intelligent entities backed by Large Language Models (LLMs), capable of reasoning, responding to events, automating tasks (e.g., chatbots, auto-traders), and coordinating in multi-agent systems. They perform complex, intelligent, or interactive tasks, acting as the active logic or "brain" within the platform. ### 6. Deploy + Run Agentic Systems The overarching environment responsible for deploying and operating all components (Services, MCP Servers, AI Agents). ### 7. Sandbox Deployment A controlled, secure, and isolated environment facilitating the deployment of components for iterative testing and refinement before production deployment. ### 8. Execution Sandbox A secure, isolated runtime environment that ensures secure execution and maintains state/data persistence, crucial for testing stateful applications and iterative development. It also provides diagnostic data for debugging, performance monitoring, and iterative improvements. ### 9. Feedback / Logs Diagnostic outputs from the Execution Sandbox, essential for developers to understand system behavior, identify issues, and inform iterative improvements. ### 10. Iterate The cyclical process of refining components based on feedback, logs, and insights from previous deployments until satisfactory outcomes are achieved. ### 11. Security Coach An integrated security tool that performs real-time threat modeling, analyzing sandboxed applications for potential vulnerabilities, thereby proactively enhancing the system's security. # Operators as Infrastructure Providers Source: https://docs.capx.ai/capx-cloud/core-concepts/operators Operators serve as the backbone of Capx Cloud’s decentralized compute layer. Operators are the custodians of the Capx Cloud network, managing the infrastructure that keeps everything running smoothly. Their responsibilities extend across multiple layers of the network, ensuring the stability, scalability, and security of decentralized services. Operators play a crucial role in maintaining node uptime, managing upgrades, and safeguarding the infrastructure against threats. They are not merely random nodes; they are vetted entities who: * **Opt into Vaults and Networks**: After registration, operators must opt into specific vaults to gain access to staked collateral and into particular networks (like Capx Cloud) to become eligible for task allocations. Through this process, operators signal where they want to provide their services and under what economic terms. * **Performance Tracking**: Every operator’s performance—**uptime, compliance with SLAs, correctness of task execution**—is continuously monitored. Operators that maintain exceptional standards enjoy higher trust, better task allocation opportunities, and greater financial rewards. **Key Responsibilities:** * **Infrastructure Management:** Operators oversee the setup, configuration, and maintenance of nodes, ensuring optimal performance and minimal downtime. * **Security Enforcement:** They implement security protocols to protect nodes from threats and ensure data integrity. * **Governance Participation:** Operators engage in the network's governance processes, contributing to decision-making on protocol upgrades, policy changes, and other critical matters. Through the Symbiotic protocol, operators can accept stakes from diverse partners via unified vaults. This system enables operators to run a single infrastructure for multiple stakeholders without the complexity of separate setups. By doing so, operators improve resource efficiency while broadening access to network services for stakers and users alike. ## Types of Operator Nodes Operators can run different types of nodes, each serving a unique purpose within the Capx Cloud ecosystem. The main types include: Performer Nodes are the engine of the Capx Cloud network, responsible for executing the core AI computations and tasks submitted by users Attestor Nodes serve as the Capx Cloud’s quality assurance mechanism, validating tasks executed by Performer Nodes. # Performer Nodes Source: https://docs.capx.ai/capx-cloud/core-concepts/performer Performer Nodes are the engine of the Capx Cloud network, responsible for executing the core AI computations and tasks submitted by users. These nodes form the foundation of the decentralized infrastructure, ensuring tasks are processed efficiently, reliably, and at scale. Their role is vital for supporting AI-driven applications and other AI-based operations. When a user submits a task—such as running an AI model, processing data, or performing complex calculations—the Performer Node undertakes the execution. **Key Responsibilities:** * **Task Execution:** Upon receiving a task, the Performer Node utilizes its computational resources to process and complete the task efficiently. * **Proof of Task Generation:** After completing the task, the node generates a cryptographic proof, known as the Proof of Task, which serves as verifiable evidence of the task's execution. * **Result Dissemination:** The Performer Node then broadcasts the task results and the Proof of Task to the network, ensuring transparency and enabling subsequent validation. **Importance in the Network:** The efficiency and reliability of Performer Nodes are crucial, as they directly impact the network's ability to handle complex computations and deliver timely results to users. Performer Nodes regularly communicate with other components in the Capx Cloud, particularly Attestor Nodes, to ensure the integrity of their output. This continuous verification cycle establishes trust and minimizes the risk of fraudulent or incorrect task execution. # Resolvers Source: https://docs.capx.ai/capx-cloud/core-concepts/resolver Resolvers are specialized entities responsible for resolving disputes within the Capx Cloud network. They serve as arbiters, handling disputes and overseeing slashing incidents—penalties imposed for malicious or faulty behavior when a Performer Node fails to meet task execution standards. Resolvers provide an impartial mechanism for reviewing these incidents to ensure that penalties are applied fairly and in accordance with network policies. **Key Responsibilities:** * **Dispute Resolution:** Resolvers review conflicts arising from task executions, validations, or other network activities, providing impartial judgments. * **Slashing Oversight:** They assess slashing incidents to confirm that penalties are warranted and executed fairly. * **Policy Enforcement:** Resolvers ensure that all actions taken within the network adhere to established rules and guidelines, maintaining fairness and transparency. Resolvers operate under predefined agreements between networks and vaults. Depending on the network’s risk tolerance, multiple resolvers may collaborate to reach a consensus before approving or vetoing a slashing event. This arrangement provides additional security guarantees for stakeholders, as decisions are made transparently and through a decentralized process. **Importance in the Network:** By providing a structured mechanism for dispute resolution and penalty enforcement, Resolvers uphold the network. Allowing for flexible, scalable governance structures tailored to the needs of different protocols within the Capx Cloud ecosystem. # Symbiotic Protocol Source: https://docs.capx.ai/capx-cloud/core-concepts/symbiotic To support the economic backbone of this decentralized ecosystem, **Capx Cloud integrates with [Symbiotic](https://symbiotic.fi)-a shared security protocol designed to provide flexible (re)staking infrastructure**. Symbiotic simplifies the sourcing of economic security for networks like Capx Cloud by offering a framework where operators and stakers can commit collateral to multiple networks at once, thereby increasing overall capital efficiency. At its core, Symbiotic streamlines the process of operator registration, stake management, and slashing adjudication. Instead of custom solutions for each network, **Symbiotic presents a universal, permissionless layer where participants can freely allocate capital, register as operators, and interact with multiple networks in parallel.** * **(Re)Staking Infrastructure**: Symbiotic supports repurposing of staked assets (e.g., from Ethereum validators) for additional use cases, like providing security to Capx Cloud. * **Vaults and Operator Registries**: Operators register once in Symbiotic’s OperatorRegistry and can then serve multiple networks. Vaults serve as stake pools, holding collateral and enforcing withdrawal and epoch rules. * **Resolvers for Dispute Resolution**: Should conflicts arise over slashing incidents, resolvers—neutral arbitration entities—step in to ensure fairness, reducing the likelihood of arbitrary or malicious penalties. ## Symbiotic Components The Symbiotic protocol introduces three key components that are essential for the operation and security of Capx Cloud: These are the staking pools where operators deposit their collateral. They enforce rules for withdrawals and epochs, ensuring that the staked assets are managed securely and transparently. These are the individuals or entities that provide the infrastructure for Capx Cloud. They register once in the Symbiotic OperatorRegistry and can then serve multiple networks, enhancing their operational efficiency. These are neutral arbitration entities that step in to resolve disputes, particularly in cases of slashing incidents. They ensure that penalties are fair and not arbitrary or malicious. # Vaults as Economic Hubs Source: https://docs.capx.ai/capx-cloud/core-concepts/vaults **Vaults are specialized smart contracts within Symbiotic’s ecosystem, designed to hold and manage staked assets on behalf of stakers**. Each vault enforces a particular set of parameters—such as epoch duration (time intervals that govern certain operational resets, like when slashing becomes final or when withdrawals are allowed), maximum deposit limits, and the chosen delegation model. * **Staking and Delegation Models**: Vaults allow stakers to deposit assets (e.g., tokens) and have these assets delegated to operators and networks. Depending on the selected delegation model, **stake can be spread across multiple operators, supporting multiple networks simultaneously**. * **Determining Economic Weight**: When Capx Cloud’s services need to assess how much financial backing each operator commands, they query these vaults. **The total staked amount and its distribution effectively measure an operator’s economic weight and credibility**. Operators who secure higher stakes are not only more valuable to the network but also bear a greater financial risk, encouraging reliable and honest behavior. # Foundational Concepts Source: https://docs.capx.ai/capx-cloud/foundational-concepts ## Tokenized AI Agents and On-Chain Compute Coordination The core idea behind Capx Cloud is to represent AI applications as tokenized, on-chain entities. By treating each AI agent as a set of tradeable tokens, developers and users can collectively own and govern the application’s fate. This tokenization enables fractional ownership, allowing a broad community—ranging from early adopters and investors to end-users and developers—to share in the risks and rewards of a particular AI service onchain. Moreover, it sets the stage for decentralized decision-making, as token holders can propose changes, vote on key parameters, and directly influence the application’s evolution. ### Key Benefits of Tokenized AI Agents
| Concept | Description | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | **Fractional Ownership** | Multiple stakeholders can own tokens representing shares in the AI application, distributing both financial exposure and potential profit. | | **Collective Governance** | Token holders collectively shape the application’s direction, feature set, and deployment configurations. | | **Decentralized Marketplace** | Many operators compete to host AI workloads, improving resilience and driving down costs. | | **On-Chain Coordination** | Smart contracts manage deployment assignments, track operator reputation, and enforce governance decisions. | Under the hood, AI agents rely on a decentralized marketplace of operators. Rather than anchoring all workloads to a single cloud provider, Capx Cloud introduces competition and redundancy. Operators bid for the right to host AI workloads, and their performance is continuously measured and verified. Over time, this competitive environment drives higher quality of service, better uptime, and more cost-efficient deployment, all orchestrated by smart contracts that ensure fairness and transparency. ## Restaking and Shared Security One of the key innovations in this architecture is the concept of **restaking**. In traditional models, each new network or use case requires fresh collateral from participants. Restaking changes this dynamic. By allowing already-staked assets to serve multiple purposes, operators and stakers can amplify their economic footprint, ultimately bringing more security to the ecosystem without linearly increasing costs. ### How Restaking Improves Security and Efficiency:
| Concept | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Capital Efficiency** | Restaking enables stakers and operators to deploy their economic capital more effectively, supporting multiple networks (including Capx Cloud) without sourcing new funds for each. | | **Incentive Alignment** | Operators, by having “skin in the game,” are financially incentivized to maintain optimal performance. Poor service or malicious actions lead to immediate, on-chain penalties (slashing). | | **Robust Security** | Multiple networks share security from a common pool of staked collateral, making the ecosystem more resilient and reducing vulnerability to attacks or collusion. | Restaking aligns incentives more directly than ever before. With collateral on the line, operators must maintain high standards of reliability, honesty, and performance. Any misbehavior—such as prolonged downtime, tampering with deployed applications, or failing to produce proofs of correct execution—risks losing staked assets. This direct financial stake in the outcome ensures that operators remain motivated to provide optimal service. # Getting Started Source: https://docs.capx.ai/capx-cloud/getting-started Learn how to get started with Capx Cloud, including setting up your environment and deploying your first AI agent. ### Creating an Account & API Keys 1. **Visit the Capx Developer Portal (Link to be provided).** 2. **Connect Your Wallet:** Authenticate using your Capx Chain compatible wallet (e.g., MetaMask). 3. **Register for Cloud Services:** Complete any necessary registration steps. 4. **Generate API Keys:** Navigate to the API section in your account dashboard and generate new API keys. * **Important:** Store your API secret key securely, as it will not be shown again. 5. **Fund Your Account (if applicable):** Details on how to deposit CAPX tokens or other accepted currencies to pay for services. # Capx Cloud: Decentralized Infrastructure for the AI Era Source: https://docs.capx.ai/capx-cloud/introduction ## Why Capx Cloud? As AI applications proliferate, their compute and hosting demands continue to grow, often concentrating power in large, centralized cloud providers. This raises concerns around trust, data sovereignty, cost, and resilience. Blockchain and decentralized finance (DeFi) have demonstrated how trust and incentives can be algorithmically distributed. The emerging frontier is to merge AI workloads with decentralized infrastructure—ensuring that these AI products are not only scalable and high-performance, but also trust-minimized, community-governed, and economically aligned with stakeholders. ## Vision and Goals Capx Cloud seeks to provide: * **Decentralized Infrastructure at Scale:** Combining cloud-grade performance with trust-minimized provisioning. * **Developer-Friendly Experience:** Seamless deployments using familiar languages and frameworks, abstracting away complexity. * **Tokenized Ownership and Governance:** AI products become on-chain assets governed by stakeholders, aligning incentives and distributing rewards. * **Incentive-Backed Reliability:** Operators are economically motivated to maintain uptime and honesty, enforced by staking and slashing contracts onchain. ## How Capx Cloud Complements the Ecosystem Capx Cloud is intricately linked with Capx Chain and Capx SuperApp to create a cohesive ecosystem for AI agents and services. Here's how they interconnect: * **With Capx Chain:** * **Settlement & Payments:** Capx Chain facilitates payments for services consumed on Capx Cloud and the distribution of rewards to infrastructure providers, typically using the CAPX token. * **Identity & Registration:** AI Agents deployed on Capx Cloud can have their identities and metadata registered and tokenized as NFTs on Capx Chain. * **Service Agreement & Attestation:** Smart contracts on Capx Chain can govern service level agreements (SLAs) and record attestations of work done by Cloud providers. * **With Capx SuperApp:** * **Discovery & Management:** Users can discover AI agents and services running on Capx Cloud through the SuperApp. * **Interaction Interface:** The SuperApp can provide a user-friendly interface for interacting with agents and services hosted on Capx Cloud. * **Deployment Dashboard (for Developers):** Developers might use a dashboard (potentially integrated into or linked from the SuperApp) to deploy and manage their agents and services on Capx Cloud. ## Key Benefits of Capx Cloud: * **Democratized Access:** Lowers the barrier to entry for accessing sophisticated AI compute and cloud resources, fostering innovation. * **Cost-Effectiveness:** Aims to provide more competitive pricing compared to traditional centralized cloud providers by leveraging a distributed network of providers. * **Decentralization & Censorship Resistance:** Reduces reliance on single points of failure and control, making services more resilient and open. * **Enhanced Security:** Leverages cryptographic methods, potential for confidential compute, and decentralized consensus for secure execution environments. * **Scalability:** Designed to scale globally by onboarding a diverse range of infrastructure providers. * **Provider Incentivization:** Offers economic incentives for individuals and data centers to contribute their idle or dedicated compute resources to the network. # CLI Commands Source: https://docs.capx.ai/capx-compose/cli-reference Capx Compose command line interface reference ## Main Command ### capx-compose Create a new Next.js project with selected plugins. ```bash theme={null} capx-compose [options] ``` **Arguments:** * `project-name` - Name of the project directory to create (required) **Options:** * `--plugins ` - Comma-separated list of plugins to include * `--use-pnpm` - Use pnpm as package manager * `--use-yarn` - Use Yarn as package manager * `--skip-install` - Skip automatic dependency installation * `--eslint` - Include ESLint configuration * `--no-eslint` - Skip ESLint configuration * `-y, --yes` - Accept all defaults (non-interactive mode) * `--dependency-strategy ` - Dependency resolution strategy (smart|highest|lowest|compatible) * `--silent` - Suppress enhanced output **Examples:** ```bash theme={null} # Interactive mode capx-compose my-app # With specific plugins capx-compose my-app --plugins=vercel-ai,supabase # Multiple plugins with package manager capx-compose my-app --plugins=solana,firebase --use-pnpm # Skip installation capx-compose my-app --plugins=goat,evm --skip-install # Accept defaults capx-compose my-app -y ``` ## Using with npx The recommended way to use Capx Compose without global installation: ```bash theme={null} npx capx-compose@latest [options] ``` **Examples:** ```bash theme={null} # Latest version npx capx-compose@latest my-app # Specific version npx capx-compose@0.1.1 my-app # With plugins npx capx-compose@latest my-app --plugins=vercel-ai ``` ## Plugin Commands ### `plugins list` List all available plugins. ```bash theme={null} capx-compose plugins list [options] ``` **Example:** ```bash theme={null} # List all valid plugins capx-compose plugins list ``` ### `plugins show` Show details for a specific plugin. ```bash theme={null} capx-compose plugins show ``` **Arguments:** * `plugin` - Name of the plugin to show details for **Example:** ```bash theme={null} # Show vercel-ai plugin details capx-compose plugins show vercel-ai # Show supabase plugin details capx-compose plugins show supabase ``` # Overview Source: https://docs.capx.ai/capx-compose/index Capx Compose is a powerful CLI scaffolding tool that generates production-ready Next.js applications with pre-configured AI and blockchain integrations. Build once, deploy everywhere with enterprise-grade templates. ## What is Capx Compose? Capx Compose is an **enterprise-grade scaffolding tool** that: * Generates production-ready Next.js 14+ applications in seconds * Seamlessly integrates cutting-edge AI and blockchain technologies * Provides battle-tested templates with security best practices * Includes comprehensive examples and documentation * Offers smart dependency management and conflict resolution ## Key Features * **⚡ Lightning Fast**: Generate full-stack applications in under 30 seconds * **🔌 Modular Architecture**: 10+ pre-built plugins with seamless interoperability * **🛡️ Enterprise Ready**: Security-first approach with production optimizations * **🤖 AI-Native**: Built-in support for LLMs, agents, and AI workflows * **⛓️ Multi-Chain**: Support for Solana, EVM, Sui, and more blockchains * **📚 Rich Examples**: Every integration includes working, documented code ## Plugin Ecosystem ### AI * **vercel-ai**: Stream-first AI experiences with Vercel AI SDK ### Dev Kits * **goat**: Autonomous agents with on-chain capabilities * **solana-agent-kit**: Specialized agents for Solana ecosystem ### Blockchain Infrastructure * **solana**: Complete Solana dApp toolkit with wallet integration * **evm**: Multi-chain EVM support (Ethereum, Polygon, Base, Arbitrum) * **sui**: Next-gen blockchain with Move smart contracts ### Data & Backend * **supabase**: PostgreSQL with real-time subscriptions and vector embeddings * **firebase**: Serverless NoSQL with Firebase ecosystem * **vercel-kv**: Edge-optimized Redis-compatible storage ### Authentication * **privy**: Seamless Web3 auth with embedded wallets and social login ## Quick Start ```bash theme={null} # Create with interactive CLI npx capx-compose@latest my-app # Or specify plugins directly npx capx-compose@latest my-app --plugins=vercel-ai,solana,supabase # Navigate and configure cd my-app cp .env.example .env.local # Launch development server npm run dev ``` ## Generated Project Structure ``` my-app/ ├── src/ │ ├── app/ # Next.js App Router │ ├── components/ # Reusable UI components │ ├── lib/ # Core utilities and configs │ ├── hooks/ # Custom React hooks │ └── styles/ # Global styles and themes ├── public/ # Static assets ├── contracts/ # Smart contracts (if applicable) ├── .env.example # Environment template ├── package.json # Optimized dependencies └── README.md # Custom documentation ``` ## Powerful Combinations Capx Compose intelligently resolves dependencies and suggests optimal stacks: ### AI-Powered dApps * `vercel-ai + solana` - AI-enhanced Solana applications * `goat + evm` - Autonomous agents for Ethereum * `solana-agent-kit + vercel-kv` - Scalable Solana agents ### Full-Stack Web3 * `privy + supabase + evm` - Complete Web3 SaaS stack * `firebase + solana` - Real-time blockchain applications * `vercel-kv + sui` - High-performance Sui dApps ## Why Choose Capx Compose? ### For Developers * **Open Source** : Transparent and community driven * **10x Faster Setup**: From idea to running app in minutes * **Pre-configured Templates**: Everything works out of the box * **Type-Safe**: Full TypeScript with strict mode * **Best Practices**: ESLint, Prettier, Husky pre-configured ### For Teams * **Open Source Contribution** : Extend the SDK by adding your stack with working examples * **Consistent Standards**: Unified project structure across teams * **Reduced Onboarding**: New developers productive immediately * **Maintainable**: Clean architecture with clear separation of concerns * **Scalable**: Production-optimized from day one # Installation Source: https://docs.capx.ai/capx-compose/installation Install Capx Compose to scaffold your Next.js project ## Prerequisites Before using Capx Compose, ensure you have: * **Node.js** 18.0.0 or later * **npm** 7.0.0 or later (or yarn/pnpm) * **Git** for version control ### Quick Start (Recommended) Use npx to run Capx Compose without installation: ```bash theme={null} npx capx-compose@latest my-app ``` This will: 1. Download the latest version of Capx Compose 2. Start the interactive project setup 3. Generate your project structure 4. Install dependencies (unless skipped) ### Global Installation (Optional) If you prefer to install globally: ```bash theme={null} # Install globally npm install -g capx-compose # Create a project capx-compose my-app ``` ### Using Different Package Managers ```bash theme={null} # With Yarn yarn create capx-compose my-app # With pnpm pnpm create capx-compose my-app ``` # EVM Source: https://docs.capx.ai/capx-compose/plugins/evm Build decentralized applications for Ethereum, Polygon, Arbitrum, Optimism, and other EVM-compatible chains. ## Features * Multi-chain support * Wallet connection (MetaMask, WalletConnect, Coinbase) * Smart contract interactions * Token operations (ERC20, ERC721, ERC1155) * Gas optimization * ENS integration ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins=evm cd my-app npm run dev ``` ## Configuration ```env theme={null} NEXT_PUBLIC_ALCHEMY_ID=your_alchemy_id NEXT_PUBLIC_WALLET_CONNECT_ID=your_wc_id NEXT_PUBLIC_DEFAULT_CHAIN=mainnet ``` ## Wallet Setup with Wagmi ```typescript theme={null} import { createConfig, configureChains } from 'wagmi'; import { mainnet, polygon, arbitrum, optimism } from 'wagmi/chains'; import { alchemyProvider } from 'wagmi/providers/alchemy'; import { publicProvider } from 'wagmi/providers/public'; const { chains, publicClient } = configureChains( [mainnet, polygon, arbitrum, optimism], [ alchemyProvider({ apiKey: process.env.NEXT_PUBLIC_ALCHEMY_ID }), publicProvider() ] ); export const wagmiConfig = createConfig({ autoConnect: true, connectors: [ new MetaMaskConnector({ chains }), new WalletConnectConnector({ chains, options: { projectId: process.env.NEXT_PUBLIC_WALLET_CONNECT_ID, }, }), ], publicClient, }); ``` ## Smart Contract Interactions ### Read Contract ```typescript theme={null} import { useContractRead } from 'wagmi'; function useTokenBalance(address: string) { const { data, isError, isLoading } = useContractRead({ address: TOKEN_CONTRACT_ADDRESS, abi: ERC20_ABI, functionName: 'balanceOf', args: [address], }); return { balance: data, isError, isLoading }; } ``` ### Write Contract ```typescript theme={null} import { useContractWrite, usePrepareContractWrite } from 'wagmi'; function TransferToken() { const { config } = usePrepareContractWrite({ address: TOKEN_CONTRACT_ADDRESS, abi: ERC20_ABI, functionName: 'transfer', args: [recipientAddress, amount], }); const { write, isLoading } = useContractWrite(config); return ( ); } ``` ## Using Ethers.js ```typescript theme={null} import { ethers } from 'ethers'; async function deployContract() { const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const Contract = new ethers.ContractFactory(abi, bytecode, signer); const contract = await Contract.deploy(); await contract.waitForDeployment(); return contract.target; } ``` ## Token Operations ### ERC20 Token Interactions ```typescript theme={null} async function approveToken(spender: string, amount: bigint) { const contract = new ethers.Contract(tokenAddress, ERC20_ABI, signer); const tx = await contract.approve(spender, amount); await tx.wait(); } async function getTokenMetadata(address: string) { const contract = new ethers.Contract(address, ERC20_ABI, provider); const [name, symbol, decimals] = await Promise.all([ contract.name(), contract.symbol(), contract.decimals(), ]); return { name, symbol, decimals }; } ``` ### NFT (ERC721) Operations ```typescript theme={null} async function mintNFT(to: string, tokenURI: string) { const contract = new ethers.Contract(nftAddress, ERC721_ABI, signer); const tx = await contract.safeMint(to, tokenURI); const receipt = await tx.wait(); // Get token ID from event const event = receipt.logs.find(log => log.eventName === 'Transfer'); return event.args.tokenId; } async function getNFTMetadata(tokenId: number) { const contract = new ethers.Contract(nftAddress, ERC721_ABI, provider); const uri = await contract.tokenURI(tokenId); const response = await fetch(uri); return response.json(); } ``` ## Best Practices 1. **Gas Estimation**: Always estimate gas before transactions 2. **Error Handling**: Handle wallet rejections gracefully 3. **Chain Switching**: Support multiple chains seamlessly 4. **RPC Fallbacks**: Use multiple RPC providers 5. **Transaction Monitoring**: Track transaction status ## Resources * [Ethereum Documentation](https://ethereum.org/developers) * [Wagmi Documentation](https://wagmi.sh/) * [Ethers.js Documentation](https://docs.ethers.org/) * [Viem Documentation](https://viem.sh/) # Firebase Source: https://docs.capx.ai/capx-compose/plugins/firebase Build serverless applications with Firebase ## Features * Firestore NoSQL database * Real-time data synchronization * Authentication providers * Cloud Functions * Cloud Storage * Firebase Hosting ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins= firebase cd my-app npm run dev ``` ## Configuration ```env theme={null} NEXT_PUBLIC_FIREBASE_API_KEY=your_api_key NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your_auth_domain NEXT_PUBLIC_FIREBASE_PROJECT_ID=your_project_id NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your_storage_bucket NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your_sender_id NEXT_PUBLIC_FIREBASE_APP_ID=your_app_id ``` ## Firebase Initialization ```typescript theme={null} import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; import { getFirestore } from 'firebase/firestore'; import { getStorage } from 'firebase/storage'; import { getFunctions } from 'firebase/functions'; const firebaseConfig = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, }; const app = initializeApp(firebaseConfig); export const auth = getAuth(app); export const db = getFirestore(app); export const storage = getStorage(app); export const functions = getFunctions(app); ``` ## Authentication ### Email/Password ```typescript theme={null} import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from 'firebase/auth'; async function signUp(email: string, password: string) { try { const userCredential = await createUserWithEmailAndPassword( auth, email, password ); return userCredential.user; } catch (error) { throw error; } } async function signIn(email: string, password: string) { const userCredential = await signInWithEmailAndPassword( auth, email, password ); return userCredential.user; } async function logout() { await signOut(auth); } ``` ### Social Providers ```typescript theme={null} import { GoogleAuthProvider, GithubAuthProvider, signInWithPopup } from 'firebase/auth'; async function signInWithGoogle() { const provider = new GoogleAuthProvider(); const result = await signInWithPopup(auth, provider); return result.user; } async function signInWithGitHub() { const provider = new GithubAuthProvider(); const result = await signInWithPopup(auth, provider); return result.user; } ``` ### Auth State Hook ```typescript theme={null} import { onAuthStateChanged, User } from 'firebase/auth'; function useAuth() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { setUser(user); setLoading(false); }); return unsubscribe; }, []); return { user, loading }; } ``` ## Firestore Database ### CRUD Operations ```typescript theme={null} import { collection, doc, addDoc, getDoc, getDocs, updateDoc, deleteDoc, query, where, orderBy, limit } from 'firebase/firestore'; // Create async function createDocument(collectionName: string, data: any) { const docRef = await addDoc(collection(db, collectionName), { ...data, createdAt: new Date(), }); return docRef.id; } // Read single async function getDocument(collectionName: string, id: string) { const docRef = doc(db, collectionName, id); const docSnap = await getDoc(docRef); if (docSnap.exists()) { return { id: docSnap.id, ...docSnap.data() }; } return null; } // Read multiple with query async function getDocuments(collectionName: string, filters?: any) { let q = collection(db, collectionName); if (filters?.where) { q = query(q, where(...filters.where)); } if (filters?.orderBy) { q = query(q, orderBy(...filters.orderBy)); } if (filters?.limit) { q = query(q, limit(filters.limit)); } const querySnapshot = await getDocs(q); return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); } // Update async function updateDocument( collectionName: string, id: string, data: any ) { const docRef = doc(db, collectionName, id); await updateDoc(docRef, { ...data, updatedAt: new Date(), }); } // Delete async function deleteDocument(collectionName: string, id: string) { await deleteDoc(doc(db, collectionName, id)); } ``` ## Best Practices 1. **Security Rules**: Always implement proper security rules 2. **Indexing**: Create composite indexes for complex queries 3. **Batch Operations**: Use batch writes for multiple operations 4. **Caching**: Implement proper caching strategies 5. **Error Handling**: Handle offline scenarios gracefully ## Resources * [Firebase Documentation](https://firebase.google.com/docs) * [Firebase Console](https://console.firebase.google.com/) * [Firebase Extensions](https://firebase.google.com/products/extensions) # GOAT Agent Toolkit Source: https://docs.capx.ai/capx-compose/plugins/goat It enables AI agents to interact with blockchain protocols, DeFi platforms, and smart contracts autonomously. ## Features * Multi-chain agent support * DeFi protocol integrations * Wallet management for agents * Tool creation framework * LLM-agnostic design * Transaction simulation ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins= goat cd my-app npm run dev ``` ## Configuration ```env theme={null} OPENAI_API_KEY=sk-... ALCHEMY_API_KEY=your_alchemy_key WALLET_PRIVATE_KEY=0x... ``` ## Basic Agent Setup ```typescript theme={null} import { GOAT } from '@goat-sdk/core'; import { openai } from '@goat-sdk/openai'; import { ethereum } from '@goat-sdk/ethereum'; const goat = new GOAT({ llm: openai({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4-turbo', }), tools: [ ethereum({ network: 'mainnet', rpcUrl: `https://eth-mainnet.alchemyapi.io/v2/${process.env.ALCHEMY_API_KEY}`, wallet: { privateKey: process.env.WALLET_PRIVATE_KEY, }, }), ], }); ``` ## Creating Custom Tools ```typescript theme={null} import { Tool } from '@goat-sdk/core'; import { z } from 'zod'; const priceFeedTool: Tool = { name: 'get_token_price', description: 'Get current price of a token', parameters: z.object({ symbol: z.string().describe('Token symbol (e.g., ETH, BTC)'), currency: z.string().default('USD'), }), execute: async ({ symbol, currency }) => { const response = await fetch( `https://api.coingecko.com/api/v3/simple/price?ids=${symbol}&vs_currencies=${currency}` ); const data = await response.json(); return data[symbol.toLowerCase()][currency.toLowerCase()]; }, }; goat.addTool(priceFeedTool); ``` ## DeFi Operations ### Uniswap Integration ```typescript theme={null} import { uniswap } from '@goat-sdk/uniswap'; const uniswapTool = uniswap({ network: 'mainnet', version: 'v3', slippage: 0.5, // 0.5% }); goat.addTool(uniswapTool); // Agent can now execute swaps const result = await goat.execute( 'Swap 0.1 ETH for USDC with minimal slippage' ); ``` ## Multi-Chain Support ```typescript theme={null} import { ethereum, polygon, arbitrum } from '@goat-sdk/chains'; const multiChainGoat = new GOAT({ llm: openai({ apiKey: process.env.OPENAI_API_KEY }), chains: [ ethereum({ rpcUrl: process.env.ETH_RPC }), polygon({ rpcUrl: process.env.POLYGON_RPC }), arbitrum({ rpcUrl: process.env.ARBITRUM_RPC }), ], }); // Agent can work across chains await multiChainGoat.execute( 'Bridge 100 USDC from Ethereum to Polygon using the cheapest route' ); ``` ## Safety Features ```typescript theme={null} const safeGoat = new GOAT({ llm: openai({ apiKey: process.env.OPENAI_API_KEY }), safety: { maxTransactionValue: '1000', // Max $1000 per transaction requireConfirmation: true, whitelist: { contracts: ['0x...', '0x...'], // Only interact with these tokens: ['ETH', 'USDC', 'DAI'], }, simulateBeforeExecute: true, }, }); // Set up confirmation handler safeGoat.onConfirmationRequired(async (action) => { console.log('Confirmation required for:', action); // Implement user confirmation logic return confirm(`Execute: ${action.description}?`); }); ``` ## Best Practices 1. **Safety First**: Always use transaction simulation 2. **Rate Limiting**: Implement proper rate limits for API calls 3. **Error Recovery**: Build robust error handling 4. **Monitoring**: Track all agent actions 5. **Testing**: Thoroughly test on testnets first ## Resources * [GOAT Documentation](https://docs.goat.dev/) * [Example Agents](https://github.com/goat-sdk/examples) * [Tool Registry](https://registry.goat.dev/) # Overview Source: https://docs.capx.ai/capx-compose/plugins/index Capx Compose provides production-ready plugins that add specific functionality to your Next.js project. Each plugin includes working examples, proper configuration, and all necessary dependencies. # Available Plugins ## AI Streaming AI chat with Vercel AI SDK ## Dev Kits Autonomous agents with blockchain capabilities Solana-specific agent framework ## Blockchain Solana wallet and dApp development Ethereum and EVM-compatible chains Sui blockchain with Move contracts ## Authentication Web3 authentication ## Data & Backend PostgreSQL with real-time and auth NoSQL database and Firebase services Redis-compatible key-value storage ## Plugin Features Each plugin provides: #### 📁 Complete File Structure * Working example pages * API routes (if needed) * Utility functions * Type definitions #### 📦 Dependencies * Production packages * Development tools * Type definitions * Peer dependencies #### 🔧 Configuration * Environment variables template * Config files * Build settings * TypeScript types #### 📚 Documentation * README with setup instructions * Code comments * Usage examples * Best practices ## Environment Variables Each plugin requires specific environment variables: ### AI & Dev-Kit Plugins ```env theme={null} # vercel-ai, goat OPENAI_API_KEY=sk-... # goat specific GOAT_CHAIN=evm WALLET_PRIVATE_KEY=0x... RPC_PROVIDER_URL=https://... ``` ### Blockchain Plugins ```env theme={null} # solana NEXT_PUBLIC_SOLANA_NETWORK=devnet NEXT_PUBLIC_RPC_ENDPOINT=https://api.devnet.solana.com # evm NEXT_PUBLIC_ETHEREUM_NETWORK=sepolia NEXT_PUBLIC_INFURA_PROJECT_ID=... # privy NEXT_PUBLIC_PRIVY_APP_ID=... ``` ### Data & Backend Plugins ```env theme={null} # supabase NEXT_PUBLIC_SUPABASE_URL=... NEXT_PUBLIC_SUPABASE_ANON_KEY=... # firebase NEXT_PUBLIC_FIREBASE_API_KEY=... NEXT_PUBLIC_FIREBASE_PROJECT_ID=... # vercel-kv KV_REST_API_URL=... KV_REST_API_TOKEN=... ``` ## Choosing Plugins ### For AI Applications * Start with `vercel-ai` for chat interfaces * Add `supabase` or `firebase` for data persistence * Use `vercel-kv` for caching ### For Web3 Applications * Choose your blockchain: `solana`, `evm`, or `sui` * Add `privy` for user authentication * Include `firebase` or `supabase` for off-chain data ### For AI + Web3 * Use `goat` for EVM/Solana AI agents * Use `solana-agent-kit` for Solana-specific agents * Combine with databases for persistence # Privy Source: https://docs.capx.ai/capx-compose/plugins/privy Privy provides seamless authentication for Web3 and Web2 users with wallet connections, social logins, and embedded wallets. ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins=privy ``` ## Configuration Add to `.env.local`: ```env theme={null} NEXT_PUBLIC_PRIVY_APP_ID=your_app_id PRIVY_APP_SECRET=your_app_secret ``` ## Basic Setup ```typescript theme={null} // app/providers.tsx 'use client'; import { PrivyProvider } from '@privy-io/react-auth'; export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ## Authentication ```typescript theme={null} import { usePrivy } from '@privy-io/react-auth'; export function AuthButton() { const { ready, authenticated, user, login, logout } = usePrivy(); if (!ready) return
Loading...
; if (authenticated) { return (

{user?.email || user?.wallet?.address}

); } return ; } ``` ## Wallet Operations ```typescript theme={null} import { useWallets } from '@privy-io/react-auth'; function WalletManager() { const { wallets } = useWallets(); const sendTransaction = async () => { if (!wallets[0]) return; const provider = await wallets[0].getEthersProvider(); const signer = provider.getSigner(); const tx = await signer.sendTransaction({ to: '0x...', value: ethers.parseEther('0.01'), }); await tx.wait(); }; return (
{wallets.map((wallet) => (

{wallet.address}

Chain: {wallet.chainId}

))}
); } ``` ## Features * **Multiple Auth Methods**: Email, wallet, social logins * **Embedded Wallets**: Auto-create wallets for users * **Session Management**: Built-in token handling * **Account Linking**: Connect multiple auth methods * **Fiat On-ramp**: Direct funding options ## Resources * [Privy Documentation](https://docs.privy.io/) * [Dashboard](https://dashboard.privy.io/) # Solana Source: https://docs.capx.ai/capx-compose/plugins/solana Build blazing-fast decentralized applications on Solana with integrated wallet support and program interactions. ## Features * Wallet connection (Phantom, Solflare, etc.) * Program (smart contract) interactions * Token operations (SPL tokens) * NFT minting and management * Transaction building and signing * Anchor framework integration ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins=solana cd my-app npm run dev ``` ## Configuration ```env theme={null} NEXT_PUBLIC_SOLANA_NETWORK=devnet NEXT_PUBLIC_RPC_ENDPOINT=https://api.devnet.solana.com PROGRAM_ID=your_program_id ``` ## Wallet Connection ```typescript theme={null} import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'; import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'; import { WalletModalProvider } from '@solana/wallet-adapter-react-ui'; import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets'; const network = WalletAdapterNetwork.Devnet; const endpoint = clusterApiUrl(network); const wallets = [new PhantomWalletAdapter()]; export function SolanaProvider({ children }) { return ( {children} ); } ``` ## Program Interactions ### Using Anchor ```typescript theme={null} import { Program, AnchorProvider, web3 } from '@project-serum/anchor'; import { useAnchorWallet } from '@solana/wallet-adapter-react'; export function useProgram() { const wallet = useAnchorWallet(); const connection = new web3.Connection(endpoint); const provider = new AnchorProvider( connection, wallet, { preflightCommitment: 'processed' } ); const program = new Program(idl, programId, provider); return program; } ``` ### Calling Program Methods ```typescript theme={null} async function initialize() { const program = useProgram(); const [pda] = await web3.PublicKey.findProgramAddress( [Buffer.from('seed')], program.programId ); await program.methods .initialize() .accounts({ user: wallet.publicKey, systemProgram: web3.SystemProgram.programId, }) .rpc(); } ``` ## Token Operations ### Create SPL Token ```typescript theme={null} import { createMint, getOrCreateAssociatedTokenAccount, mintTo } from '@solana/spl-token'; async function createToken() { const mint = await createMint( connection, payer, mintAuthority.publicKey, freezeAuthority.publicKey, 9 // Decimals ); const tokenAccount = await getOrCreateAssociatedTokenAccount( connection, payer, mint, owner.publicKey ); await mintTo( connection, payer, mint, tokenAccount.address, mintAuthority, 1000000000 // 1 token with 9 decimals ); } ``` ### Transfer Tokens ```typescript theme={null} import { transfer } from '@solana/spl-token'; async function transferTokens(from: PublicKey, to: PublicKey, amount: number) { await transfer( connection, payer, from, to, owner, amount ); } ``` ## NFT Operations ### Mint NFT with Metaplex ```typescript theme={null} import { Metaplex } from '@metaplex-foundation/js'; const metaplex = new Metaplex(connection); async function mintNFT(metadata: any) { const { nft } = await metaplex.nfts().create({ uri: metadata.uri, name: metadata.name, sellerFeeBasisPoints: 500, // 5% symbol: metadata.symbol, creators: [ { address: wallet.publicKey, share: 100, }, ], }); return nft; } ``` ## Deployment ### Mainnet Configuration ```env theme={null} NEXT_PUBLIC_SOLANA_NETWORK=mainnet-beta NEXT_PUBLIC_RPC_ENDPOINT=https://your-rpc-provider.com ``` ### Program Deployment ```bash theme={null} anchor build anchor deploy --provider.cluster mainnet ``` ## Resources * [Solana Documentation](https://docs.solana.com/) * [Anchor Framework](https://www.anchor-lang.com/) * [Solana Cookbook](https://solanacookbook.com/) * [Metaplex Documentation](https://docs.metaplex.com/) # Solana Agent Kit Plugin Source: https://docs.capx.ai/capx-compose/plugins/solana-agent Build AI agents with 60+ Solana blockchain actions ## Features * **60+ Actions**: Comprehensive Solana protocol coverage * **AI Integration**: LangChain and Vercel AI SDK support * **DeFi Protocols**: Jupiter, Orca, Raydium integration * **NFT Support**: Full collection and minting capabilities * **Blinks**: Action and transaction Blinks support * **ZK Compression**: Efficient on-chain operations ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins=solana-agent-kit cd my-app npm run dev ``` ## Configuration ```env theme={null} OPENAI_API_KEY=sk-... SOLANA_RPC_URL=https://api.mainnet-beta.solana.com AGENT_PRIVATE_KEY=[...] ``` ## Agent Setup ```typescript theme={null} import { SolanaAgentKit, createSolanaTools } from 'solana-agent-kit'; import { Keypair } from '@solana/web3.js'; // Initialize wallet const keypair = Keypair.fromSecretKey( Uint8Array.from(JSON.parse(process.env.AGENT_PRIVATE_KEY)) ); // Create agent with plugins const agent = new SolanaAgentKit( keypair, process.env.SOLANA_RPC_URL, { OPENAI_API_KEY: process.env.OPENAI_API_KEY } ); ``` ## Available Actions ### Token Operations ```typescript theme={null} // Deploy new token const token = await agent.deployToken( "My Token", // name "https://...", // metadata URI "MTK", // symbol 9, // decimals 1000000 // initial supply ); // Transfer tokens await agent.transfer( recipientAddress, amount, tokenMintAddress // optional, defaults to SOL ); // Swap tokens via Jupiter await agent.trade( outputMint, inputAmount, inputMint, slippageBps // 300 = 3% ); ``` ### NFT Operations ```typescript theme={null} // Deploy NFT collection const collection = await agent.deployCollection({ name: "My Collection", uri: "https://...", royaltyBasisPoints: 500 // 5% }); // Mint NFT await agent.mintNFT( collectionMint, metadata, recipientAddress ); ``` ### DeFi Actions ```typescript theme={null} // Stake SOL await agent.stakeWithJup(amountInSol); // Lend assets await agent.lendAsset(amount); // Request price feed const price = await agent.fetchPrice(tokenAddress); ``` ## LangChain Integration ```typescript theme={null} import { createSolanaTools } from 'solana-agent-kit/langchain'; const tools = createSolanaTools(agent); // Use with LangChain const llm = new ChatOpenAI(); const agentExecutor = await createToolCallingAgent({ llm, tools, prompt }); ``` ## Vercel AI SDK Integration ```typescript theme={null} import { solanaAgentTools } from 'solana-agent-kit/vercel'; const tools = solanaAgentTools(agent); // Use with Vercel AI const result = await generateText({ model: openai('gpt-4'), tools, prompt: 'Swap 1 SOL for USDC' }); ``` ## Best Practices 1. **Error Handling**: Always wrap operations in try-catch 2. **RPC Selection**: Use reliable RPC providers 3. **Gas Management**: Monitor transaction fees 4. **Security**: Secure private key storage ## Resources * [GitHub Repository](https://github.com/sendaifun/solana-agent-kit) * [NPM Package](https://www.npmjs.com/package/solana-agent-kit) * [Solana Documentation](https://docs.solana.com/) # Sui Source: https://docs.capx.ai/capx-compose/plugins/sui Build high-performance decentralized applications on Sui blockchain using the Move programming language. ## Features * Sui wallet integration * Move contract interactions * Object-centric programming * Sponsored transactions * zkLogin authentication * Programmable transaction blocks ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins= sui cd my-app npm run dev ``` ## Configuration ```env theme={null} NEXT_PUBLIC_SUI_NETWORK=testnet NEXT_PUBLIC_FULLNODE_URL=https://fullnode.testnet.sui.io:443 PACKAGE_ID=0x... ``` ## Wallet Connection ```typescript theme={null} import { ConnectButton, useCurrentAccount } from '@mysten/dapp-kit'; import { WalletProvider } from '@mysten/dapp-kit'; import { getFullnodeUrl, SuiClient } from '@mysten/sui.js/client'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const queryClient = new QueryClient(); const networks = { testnet: { url: getFullnodeUrl('testnet') }, mainnet: { url: getFullnodeUrl('mainnet') }, }; export function SuiProvider({ children }) { return ( {children} ); } ``` ## Move Contract Interactions ### Call Move Functions ```typescript theme={null} import { TransactionBlock } from '@mysten/sui.js/transactions'; import { useSignAndExecuteTransactionBlock } from '@mysten/dapp-kit'; function useMoveCall() { const { mutate: signAndExecute } = useSignAndExecuteTransactionBlock(); const callFunction = async () => { const tx = new TransactionBlock(); tx.moveCall({ target: `${PACKAGE_ID}::module::function`, arguments: [ tx.pure('argument1'), tx.object('0x...'), // Object ID ], }); signAndExecute( { transactionBlock: tx, options: { showEffects: true, showObjectChanges: true, }, }, { onSuccess: (result) => { console.log('Transaction successful:', result); }, } ); }; return { callFunction }; } ``` ## Object Management ### Create Objects ```typescript theme={null} async function createObject() { const tx = new TransactionBlock(); const [coin] = tx.splitCoins(tx.gas, [tx.pure(1000000)]); tx.moveCall({ target: `${PACKAGE_ID}::nft::mint`, arguments: [ tx.pure('NFT Name'), tx.pure('Description'), tx.pure('https://image.url'), coin, ], }); const result = await signAndExecute({ transactionBlock: tx }); // Get created object from results const createdObject = result.objectChanges?.find( (change) => change.type === 'created' ); return createdObject?.objectId; } ``` ### Transfer Objects ```typescript theme={null} async function transferObject(objectId: string, recipient: string) { const tx = new TransactionBlock(); tx.transferObjects( [tx.object(objectId)], tx.pure(recipient) ); await signAndExecute({ transactionBlock: tx }); } ``` ## Best Practices 1. **Object Ownership**: Understand shared vs owned objects 2. **Gas Management**: Optimize transaction batching 3. **Error Handling**: Handle Move abort codes properly 4. **Type Safety**: Use TypeScript types for Move structs 5. **Testing**: Test Move modules thoroughly ## Resources * [Sui Documentation](https://docs.sui.io/) * [Move Language Book](https://move-language.github.io/move/) * [Sui TypeScript SDK](https://sdk.mystenlabs.com/typescript) * [Sui Explorer](https://suiexplorer.com/) # Supabase Source: https://docs.capx.ai/capx-compose/plugins/supabase Full-stack applications with Supabase backend ## Features * PostgreSQL database with Row Level Security * Real-time subscriptions * Authentication with social providers * File storage with CDN * Edge Functions * Vector embeddings for AI ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins= supabase cd my-app npm run dev ``` ## Configuration ```env theme={null} NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key SUPABASE_SERVICE_KEY=your_service_key ``` ## Client Setup ```typescript theme={null} import { createClient } from '@supabase/supabase-js'; const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ); export default supabase; ``` ## Authentication ### Email/Password Auth ```typescript theme={null} async function signUp(email: string, password: string) { const { data, error } = await supabase.auth.signUp({ email, password, options: { emailRedirectTo: `${window.location.origin}/auth/callback`, }, }); return { data, error }; } async function signIn(email: string, password: string) { const { data, error } = await supabase.auth.signInWithPassword({ email, password, }); return { data, error }; } ``` ### Social Authentication ```typescript theme={null} async function signInWithProvider(provider: 'google' | 'github' | 'twitter') { const { data, error } = await supabase.auth.signInWithOAuth({ provider, options: { redirectTo: `${window.location.origin}/auth/callback`, }, }); return { data, error }; } ``` ### Session Management ```typescript theme={null} function useUser() { const [user, setUser] = useState(null); useEffect(() => { // Get initial session supabase.auth.getSession().then(({ data: { session } }) => { setUser(session?.user ?? null); }); // Listen for auth changes const { data: { subscription } } = supabase.auth.onAuthStateChange( (_event, session) => { setUser(session?.user ?? null); } ); return () => subscription.unsubscribe(); }, []); return user; } ``` ## Database Operations ### CRUD Operations ```typescript theme={null} // Create async function createPost(post: Post) { const { data, error } = await supabase .from('posts') .insert(post) .select() .single(); return { data, error }; } // Read async function getPosts() { const { data, error } = await supabase .from('posts') .select('*, author:users(name, avatar)') .order('created_at', { ascending: false }); return { data, error }; } // Update async function updatePost(id: string, updates: Partial) { const { data, error } = await supabase .from('posts') .update(updates) .eq('id', id) .select() .single(); return { data, error }; } // Delete async function deletePost(id: string) { const { error } = await supabase .from('posts') .delete() .eq('id', id); return { error }; } ``` ## Best Practices 1. **RLS Policies**: Always enable Row Level Security 2. **Type Safety**: Generate TypeScript types from schema 3. **Connection Pooling**: Use connection pooling for high traffic 4. **Caching**: Implement proper caching strategies 5. **Error Handling**: Handle network and permission errors ## Resources * [Supabase Documentation](https://supabase.com/docs) * [Supabase GitHub](https://github.com/supabase/supabase) * [SQL Editor](https://supabase.com/dashboard/project/_/sql) # Vercel AI Source: https://docs.capx.ai/capx-compose/plugins/vercel-ai Scaffolds a Next.js project with a complete AI chat interface powered by OpenAI GPT models. ## What Gets Scaffolded When you use this plugin, Capx Compose generates: ### Files Created * **Chat interface page** at `/vercel-ai` - Complete chat UI with streaming * **API route** at `/api/chat` - Backend endpoint for AI responses * **README** with setup instructions and customization guide ### Dependencies Added * `ai` - Vercel AI SDK for streaming * `@ai-sdk/openai` - OpenAI provider * UI utilities (lucide-react, class-variance-authority) * Next.js 14, React 18, TypeScript ### Features Included * ✅ Real-time streaming chat interface * ✅ OpenAI GPT-4o integration * ✅ Error handling and loading states * ✅ TypeScript types * ✅ Production-ready API route ## Quick Start ```bash theme={null} # Scaffold a new project with AI chat npx capx-compose@latest my-ai-app --plugins=vercel-ai # Navigate to project cd my-ai-app # Configure environment echo "OPENAI_API_KEY=sk-..." >> .env.local # Start development npm run dev ``` Visit `http://localhost:3000/vercel-ai` to see the chat interface. ## Environment Variables ```env theme={null} OPENAI_API_KEY=sk-your-openai-api-key ``` Get your API key from [OpenAI Platform](https://platform.openai.com/api-keys). ## Customization After scaffolding, you can: * Change the AI model in `/api/chat` * Modify the chat UI in `/vercel-ai` * Add authentication and rate limiting * Integrate with databases for message persistence ## Compatible Plugins Works well with: * `supabase` - Add user auth and message storage * `firebase` - Alternative backend with real-time sync * `vercel-kv` - Add caching for responses ## Example Combinations ```bash theme={null} # AI chat with database npx capx-compose@latest my-app --plugins=vercel-ai,supabase # AI chat with caching npx capx-compose@latest my-app --plugins=vercel-ai,vercel-kv # Full stack AI platform npx capx-compose@latest my-app --plugins=vercel-ai,firebase,vercel-kv ``` ## Resources * [Vercel AI SDK Docs](https://sdk.vercel.ai/docs) * [OpenAI API Docs](https://platform.openai.com/docs) # Vercel KV Source: https://docs.capx.ai/capx-compose/plugins/vercel-kv Redis-compatible caching and session storage with Vercel KV ## Features * Redis-compatible API * Global edge caching * Session management * Rate limiting * Pub/Sub messaging * Automatic failover ## Quick Start ```bash theme={null} npx capx-compose@latest my-app --plugins= vercel-kv cd my-app vercel env pull npm run dev ``` ## Configuration ```env theme={null} KV_URL=your_kv_url KV_REST_API_URL=your_rest_api_url KV_REST_API_TOKEN=your_rest_api_token KV_REST_API_READ_ONLY_TOKEN=your_read_only_token ``` ## Basic Setup ```typescript theme={null} import { kv } from '@vercel/kv'; // Or create custom instance import { createClient } from '@vercel/kv'; const kvClient = createClient({ url: process.env.KV_REST_API_URL, token: process.env.KV_REST_API_TOKEN, }); export default kvClient; ``` ## Key-Value Operations ### Basic Operations ```typescript theme={null} // Set value await kv.set('user:123', { name: 'John', email: 'john@example.com' }); // Set with expiration (seconds) await kv.set('session:abc', { userId: '123' }, { ex: 3600 }); // Get value const user = await kv.get('user:123'); // Delete key await kv.del('user:123'); // Check if key exists const exists = await kv.exists('user:123'); // Set multiple values await kv.mset({ 'key1': 'value1', 'key2': 'value2' }); // Get multiple values const values = await kv.mget('key1', 'key2'); ``` ### Expiration Management ```typescript theme={null} // Set expiration in seconds await kv.expire('session:abc', 3600); // Set expiration timestamp await kv.expireat('session:abc', Math.floor(Date.now() / 1000) + 3600); // Get TTL const ttl = await kv.ttl('session:abc'); // Remove expiration await kv.persist('session:abc'); ``` ## Caching Patterns ### Function Result Caching ```typescript theme={null} async function getCachedData( key: string, fetcher: () => Promise, ttl = 3600 ): Promise { // Try to get from cache const cached = await kv.get(key); if (cached) return cached; // Fetch fresh data const fresh = await fetcher(); // Store in cache await kv.set(key, fresh, { ex: ttl }); return fresh; } // Usage const userData = await getCachedData( `user:${userId}`, () => fetchUserFromDatabase(userId), 7200 // 2 hours ); ``` ## Best Practices 1. **Key Naming**: Use consistent naming conventions (e.g., `type:id:field`) 2. **TTL Strategy**: Always set TTL for temporary data 3. **Batch Operations**: Use pipeline for multiple operations 4. **Error Handling**: Implement retry logic for transient failures 5. **Monitoring**: Track cache hit rates and performance ## Resources * [Vercel KV Documentation](https://vercel.com/docs/storage/vercel-kv) * [Redis Commands Reference](https://redis.io/commands) # Quick Start Source: https://docs.capx.ai/capx-compose/quick-start Build your first AI-powered application in 5 minutes using Capx Compose ## Create Your First App ### Step 1: Generate Project Run the Capx Compose scaffolding tool: ```bash theme={null} npx capx-compose@latest my-ai-app --plugins=vercel-ai ``` This creates a Next.js project with: * Vercel AI SDK integration * OpenAI GPT streaming chat * TypeScript configuration * Tailwind CSS styling * Working example pages ### Step 2: Navigate to Project ```bash theme={null} cd my-ai-app ``` ### Step 3: Configure Environment Create your environment file: ```bash theme={null} cp .env.example .env.local ``` Edit `.env.local` and add your OpenAI API key: ```env theme={null} OPENAI_API_KEY=sk-... ``` Get your API key from [OpenAI Platform](https://platform.openai.com/api-keys). ### Step 4: Install Dependencies If dependencies weren't auto-installed: ```bash theme={null} npm install ``` ### Step 5: Start Development Server ```bash theme={null} npm run dev ``` Open [http://localhost:3000](http://localhost:3000) to see your app! ## What You Get Your generated project includes: ### Working AI Chat Interface Navigate to `/vercel-ai` to see a complete chat interface with: * Streaming responses from OpenAI * Message history * Loading states * Error handling ### Project Structure ``` my-ai-app/ ├── src/ │ ├── pages/ │ │ ├── index.tsx # Home page │ │ ├── vercel-ai.tsx # AI chat interface │ │ └── api/ │ │ └── chat.ts # AI chat endpoint │ ├── components/ # Reusable components │ └── styles/ # CSS styles ├── public/ # Static assets ├── .env.example # Environment template └── package.json # Dependencies ``` ### Pre-configured Features * **Next.js 14+** with App Router support * **TypeScript** for type safety * **Tailwind CSS** for styling * **Vercel AI SDK** for streaming * **OpenAI Integration** ready to use # Frequently Asked Questions Source: https://docs.capx.ai/capx-superapp/faq Capx Super App brings discovery, ownership, and trading of AI-agent apps together in a single, seamless hub. Think of it as the perfect blend of the AI App Store + Robinhood for AI tokens. Users can discover, use, and trade tokenized AI agents, turning them into ownable digital assets. For builders, it offers a new distribution and monetization channel; for users, it provides early access, ownership, and potential upside in the AI agents they use. AI agents are autonomous systems that perceive their environment, process information, make decisions, and take actions on your behalf to achieve specific goals. They can adapt to changes, learn from experience, and operate independently of humans in various tasks. The normal App store acts as a great discoverability platform, on the other hand Capx Super App not only helps discover the upcoming and latest AI Agent Apps but also enables users to buy and own the AI Apps they use. Turning users into part owners of tokenized AI Apps. Capx Super App that is on Capx Chain, is currently in testnet. No, you don't need real money. During the incentivized testnet, you earn $COINs (the internal point system of Capx Super App, especially introduced as part of Capx incentivized testnet program) by completing quests. These $COINs can be used for trading AI app tokens on Capx Super App. Go to the Capx Super App, and simply sign up using Telegram. Tradable AI apps are the tokenized AI apps, that can be owned and traded on the Capx Super App. As part of the incentivized testnet, all you got to do is earn \$COINs and use them to BUY/SELL AI app tokens on the Capx Super App. Go to the "Trade" section, select an AI app, click "Buy," enter the amount of \$COIN you want to spend, and place your trade order. Slippage is the price difference between when a trade is placed and when it's executed. During high network activity, your trade might fail or be delayed. You can increase the slippage percentage to ensure faster processing by allowing for slight token losses. Adjust slippage in the trade window. You can earn Coins by completing quests, inviting your friends to the Capx Super App using your referral code, and by ranking in the top 50 weekly traders. No, there are no limits — you can trade and earn as much as you like. Your referral code can be found in both the "Earn" section as well as on your Capx profile page. Capx uses a multi-tier referral system: * Parent (you) earns 100 Coins per Child you invite * Parent also earns 60 Coins when a Grandchild (your child's referral) joins Trading volume is the total value of your AI app trades. For example, if you buy for 100 $COIN and sell for 50 $COIN, your volume is 150 \$COIN. You can view daily, weekly, and all-time stats. The weekly leaderboard resets every Monday to create a level playing field and gamify the trading experience. Your all-time volume remains unaffected. The leaderboard shows the top 100 traders each week based on trading volume. The top 50 traders receive 1,000 Coins at the end of the week. Click on the profile icon (top-right corner). Your username (e.g., @xyz) and wallet address are displayed there. When you sign up via Telegram, a self-custodial wallet is automatically created using Privy and linked to your account. You retain full control though. Yes. In the wallet section, click the gear icon and select "Export Wallet" to access your private key. The wallet created as part of Capx Super App signup is your primary wallet. All your transactions and rewards are linked to this address. Yes, tokens can be transferred between Capx accounts. Yes, you can send AI app tokens to any external wallet. Click the wallet icon, ensure you're on your primary wallet, and then click the faucet icon to claim GAS tokens for transactions. # Getting Started Source: https://docs.capx.ai/capx-superapp/getting-started ### Zero friction. Instant access to the AI Builder Economy. Capx App lets you discover, interact with, and invest in tokenized AI apps — no wallet setup required. You log in with **Telegram**, and we handle the rest under the hood. This guide walks you through getting started in less than 2 minutes. *** ## 🧩 No Wallet? No Problem. Capx uses [**Privy**](https://www.privy.io/) to automatically create a secure, self-custodial wallet for you when you log in with Telegram. No seed phrases. No browser extensions. Just one click. *** ## 🔐 Step 1: Login with Telegram 1. Visit [app.capx.ai](https://app.capx.ai/) 2. Click **“Continue with Telegram”** 3. Approve the login via your Telegram app 4. That’s it — your on-chain wallet is now live and connected! > Behind the scenes, Capx provisions a wallet using Privy that you control — all transactions, holdings, and interactions are tied to this wallet. *** ## 🌍 Step 2: Explore AI Apps Once logged in: * Browse **Top Apps**, **New Listings**, or **App Categories** * Click on any app to view: * Live performance and token price * App description, strategy, and logic * Social stats, sentiment, and staking metrics AI Apps are like mini-startups — and you’re getting in early. *** ## 💸 Step 3: Invest, Stake, or Use Each app has an on-chain ERC-20 token. You can: * **Buy tokens** via the built-in swap UI * **Stake into apps** to unlock early rewards or governance rights * **Chat with apps** or access gated utilities (if enabled) All transactions are signed using your **Telegram-backed Privy wallet** — no extensions or approvals required. *** ## 🧑‍🎨 Step 4: Build Your On-Chain Persona As you use the app: * You earn **User Persona NFTs** — unique identity layers tied to your interaction history * These NFTs unlock deeper access, airdrops, or community roles across apps 📖 [Read more about Persona NFTs →](https://chatgpt.com/capx-products/capx-app/user-persona-nfts) *** ## 🛠️ Power User Tips * Use Telegram bookmarks to track favorite apps * Watch for **IOU token airdrops** for early contributors * Stake into high-potential apps to earn yield + governance rights * Your Privy wallet works across all Capx products — App, Chain, and Cloud *** ## 🤝 Support * Join our [Telegram Bot](https://t.me/capxai) to get notified of app launches * Ask questions in the [Discord](https://discord.gg/capx) * Follow [@0xCapx](https://x.com/0xcapx) for updates # Capx SuperApp: Your Gateway to the AI App Economy Source: https://docs.capx.ai/capx-superapp/introduction ## Why Capx SuperApp? The AI‑app landscape is powerful but fragmented—split across Discord bots, siloed dApps, and back‑end APIs. Capx SuperApp collapses that complexity into **one intuitive interface** so anyone can: * **Discover** cutting‑edge AI apps in seconds. * **Own** a slice of their upside via on‑chain tokens. The burgeoning world of AI apps and decentralized services, while powerful, can often feel fragmented and complex for end-users. Accessing diverse AI capabilities, managing digital assets related to them, and participating in new AI-driven economies requires a simplified, unified interface. Capx SuperApp is built to bridge this gap, providing an intuitive and engaging platform that makes the power of decentralized AI accessible to everyone, from casual users to active participants in the AI App marketplace. ## Vision & Goals The vision for Capx SuperApp is to be the premier, user-centric dApp for discovering, interacting with, and participating in the decentralized AI app economy. Its primary goals are to: * **Simplify AI App Discovery & Interaction:** Provide a seamless and intuitive platform where users can easily find, explore, and engage with a diverse array of AI apps and services. * **Foster a Vibrant AI Marketplace:** Enable users to not only interact with apps but also to discover, create, and trade AI apps and their associated tokens, cultivating a dynamic ecosystem. * **Integrate Digital Asset Management:** Offer native support for managing digital assets, including app-specific tokens (ERC20) and NFTs, within a secure and user-friendly environment. * **Drive User Engagement & Participation:** Create compelling ways for users to actively participate in the ecosystem through quests, rewards, and community-driven activities. * **Ensure a Secure & Trustworthy Experience:** Implement robust security measures for authentication and asset management, building user confidence. ## What Can You do? | 🚀 Action | 🛠 How It Works in Capx | 🌟 Benefit to You | | :------------------ | :---------------------------------------------------------- | :------------------------------------------ | | **Explore AI Apps** | Category hubs, trending boards, deep‑dive profiles | Find the right tool in minutes | | **Chat / Invoke** | Text, voice, or API calls in a consistent UI | Use agents like apps, not terminals | | **Earn & Govern** | Stake CAPX or app tokens to unlock tiers & vote on upgrades | Share the upside you create | | **Trade** | Built‑in AMM pools | Full liquidity without tab‑hopping | | **Build & Publish** | Upload a container → mint token → go live | Reach users instantly, skip infra headaches | ## Audience Snapshot * **Creators / Developers** – Tokenize and distribute apps to a ready user‑base. * **Everyday Users** – Access frictionless AI tools and earn tokens for early adoption. * **Capital Allocators** – Provide liquidity or trade high‑growth app micro‑economies. * **Infrastructure Operators** – Provide Compute and Memory for running AI apps. # Main Components of Capx SuperApp Source: https://docs.capx.ai/capx-superapp/main-components The Capx SuperApp is built upon a robust and scalable backend, featuring several key components: ### 1. **Capx Auth (Authentication System):** * **Secure Authentication:** Capx Auth utilizes a JWT (JSON Web Token)-based authentication mechanism with the RS256 algorithm. This ensures secure and standardized user authentication. * **User Management:** The system manages user accounts, including registration, login, and profile management. * **Token Management:** It handles the issuance and validation of JWTs, ensuring that users can securely access their accounts and interact with the platform. ### 2. **Referral System:** * **Multi-Level Structure:** A sophisticated multi-level referral system encourages user growth. Users can generate unique referral codes and share them. * **Automated Tracking:** The system automatically tracks and attributes referrals when new users join via referral links. * **Reward Distribution:** Rewards are distributed across multiple levels of the referral chain. * **Analytics & Reporting:** Comprehensive analytics allow users to track referral performance and earnings. ### 3. **Wallet Integration:** * **Multi-Chain Support:** Seamless blockchain integration supporting multiple chains and token standards (ERC20, ERC721). * **Asset Management:** Users can manage their digital assets (tokens and NFTs) directly within the platform. * **Real-Time Tracking:** Real-time balance tracking and transaction history are provided. ### 4. **Store and Marketplace:** * **AI app Interaction:** A marketplace for users to interact with, create, and trade AI apps. * **Dynamic Pricing:** A dynamic pricing system based on market demand for apps. * **Trending apps:** Tracking of trending apps. ### 5. **Quest and Engagement Systems:** * **Challenges & Tasks:** Users can participate in quests and challenges to earn rewards. * **Leaderboard:** A leaderboard tracks user achievements and progress. * **Daily Spin:** A daily spin mechanism adds a gamified element for regular engagement. ### 6. **Transaction and Payment Processing:** * **Top-Up System:** A robust system for managing credits and payments. * **Secure Processing:** Secure processing and recording of all transactions. * **Transaction History:** Detailed transaction histories and receipt management. # Create Account on Capx SuperApp Source: https://docs.capx.ai/capx-superapp/tutorials/create-account