# Table of Contents - [Welcome to Arch Network](#welcome-to-arch-network) - [Welcome to Arch Network](#welcome-to-arch-network) - [SDK Reference](#sdk-reference) - [πŸš€ Quick Start Guide](#-quick-start-guide) - [πŸ—οΈ Validator Setup](#-validator-setup) - [Bitcoin Integration](#bitcoin-integration) - [Architecture Overview](#architecture-overview) - [SDK Reference](#sdk-reference) - [Network Architecture](#network-architecture) - [Arch CLI Reference Guide](#arch-cli-reference-guide) - [Associated Token Account Program](#associated-token-account-program) - [System Requirements](#system-requirements) - [RPC API Reference](#rpc-api-reference) - [Introduction to the Arch Program Library (APL)](#introduction-to-the-arch-program-library-apl-) - [Writing Your First Arch Program](#writing-your-first-arch-program) - [Syscalls](#syscalls) - [Creating APL Tokens on Arch Network](#creating-apl-tokens-on-arch-network) - [ROAST and FROST Consensus](#roast-and-frost-consensus) - [APL Token Program](#apl-token-program) - [RPC Reference](#rpc-reference) - [Getting Started with the TypeScript SDK](#getting-started-with-the-typescript-sdk) - [FAQ](#faq) - [How to Write an Oracle Program](#how-to-write-an-oracle-program) - [Cross-Program Invocation (CPI)](#cross-program-invocation-cpi-) - [Instructions and Messages](#instructions-and-messages) - [Entrypoint and Handler Functions](#entrypoint-and-handler-functions) - [Account Guide](#account-guide) - [Program](#program) - [Building Your First Bitcoin Runes Swap Application](#building-your-first-bitcoin-runes-swap-application) - [How to Build a Bitcoin Lending Protocol](#how-to-build-a-bitcoin-lending-protocol) - [External Resources](#external-resources) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) - [404: This page could not be found.](#404-this-page-could-not-be-found-) --- # Welcome to Arch Network Welcome to Arch Network ======================= A Bitcoin-native computation environment that enhances Bitcoin's capabilities through specialized virtual machine operations This documentation is actively maintained. If you find any issues or have suggestions for improvements, please visit our [GitHub repository](https://github.com/arch-network/docs) . [What is Arch Network?](https://book.arch.network/docs#what-is-arch-network) ----------------------------------------------------------------------------- Arch Network is a computation environment that enhances Bitcoin's capabilities by enabling complex operations on Bitcoin UTXOs through its specialized virtual machine. Unlike Layer 2 solutions, Arch Network provides a native computation layer that works directly with Bitcoin's security model. [Choose Your Path πŸ‘‹](https://book.arch.network/docs#choose-your-path-) ------------------------------------------------------------------------ [### πŸš€ Deploy First\ \ Get your first smart contract running on Arch Network as quickly as possible](https://book.arch.network/docs/quick-start/quick-start) [### πŸ—οΈ Run a Validator\ \ Set up and run your own validator node on the Arch Network](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) ### [Network Options](https://book.arch.network/docs#network-options) [### πŸ”§ Regtest\ \ Local development environment with instant block confirmation. Perfect for development and testing.](https://book.arch.network/docs/quick-start/quick-start) [### πŸ§ͺ Testnet\ \ Test network with real Bitcoin testnet integration. For testing in a live environment.](https://book.arch.network/docs/quick-start/quick-start) [Key Features](https://book.arch.network/docs#key-features) ------------------------------------------------------------ [### Bitcoin-Native\ \ Direct integration with Bitcoin through UTXO management](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Computation Environment\ \ Execute complex programs within the Arch VM](https://book.arch.network/docs/setup-infrastructure/architecture) [### Program Development\ \ Write programs in Rust to interact with Bitcoin UTXOs](https://book.arch.network/docs/development/writing-your-first-program) [### Security\ \ Leverages Bitcoin's proven security guarantees through multi-signature validation](https://book.arch.network/docs/setup-infrastructure/network-architecture) [### Developer Tools\ \ Complete development environment with CLI tools and explorer](https://book.arch.network/docs/tools-apis/arch-cli-reference) [Prerequisites](https://book.arch.network/docs#prerequisites) -------------------------------------------------------------- Before you begin, ensure you have: * Node.js v19+ ([installation guide](https://book.arch.network/docs/quick-start/requirements) ) * Rust (latest stable) * Docker for local development * Basic understanding of [Bitcoin Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) [Core Architecture](https://book.arch.network/docs#core-architecture) ---------------------------------------------------------------------- ### [How Arch Works](https://book.arch.network/docs#how-arch-works) Arch Network consists of three main components: 1. **Network Layer** * [Network Architecture](https://book.arch.network/docs/setup-infrastructure/network-architecture) * [Bootnode](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Network discovery and peer management * [Leader Node](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Transaction coordination * [Validator Nodes](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Program execution 2. **Bitcoin Integration** * [UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Transaction tracking * State anchoring * Ownership validation * [RPC Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Bitcoin node communication * Transaction submission * Network synchronization 3. **Computation Layer** * [Programs](https://book.arch.network/docs/development/writing-your-first-program) * [Instructions](https://book.arch.network/docs/development/writing-your-first-program) * [Accounts](https://book.arch.network/docs/development/writing-your-first-program) * [System Calls](https://book.arch.network/docs/development/writing-your-first-program) * [Transaction Processing](https://book.arch.network/docs/tools-apis/sdk) * Message validation * State updates * UTXO management [πŸ›  Reference Documentation](https://book.arch.network/docs#-reference-documentation) -------------------------------------------------------------------------------------- [### API Reference\ \ RPC API Reference and Transaction Processing](https://book.arch.network/docs/tools-apis/api-reference) [### Program Examples\ \ Oracle Program and Fungible Token examples](https://book.arch.network/docs/development/writing-your-first-program) [### System Program\ \ Account Creation and Program Deployment](https://book.arch.network/docs/apl/introduction) [Need Help?](https://book.arch.network/docs#need-help) ------------------------------------------------------- [### Join Discord\ \ Get support from the community](https://discord.gg/archnetwork) [### Architecture Overview\ \ Read the Architecture Overview](https://book.arch.network/docs/setup-infrastructure/architecture) [### Example Programs\ \ View Example Programs](https://book.arch.network/docs/development/writing-your-first-program) [### API Reference\ \ Check the API Reference](https://book.arch.network/docs/tools-apis/api-reference) πŸ’‘ **Pro Tip:** Use the search function (press 's' or '/' on your keyboard) to quickly find what you're looking for in the documentation. [Associated Token Account Program\ \ Complete guide to the APL Associated Token Account Program for deterministic token account management](https://book.arch.network/docs/apl/associated-token-account) ### On this page [What is Arch Network?](https://book.arch.network/docs#what-is-arch-network) [Choose Your Path πŸ‘‹](https://book.arch.network/docs#choose-your-path-) [Network Options](https://book.arch.network/docs#network-options) [Key Features](https://book.arch.network/docs#key-features) [Prerequisites](https://book.arch.network/docs#prerequisites) [Core Architecture](https://book.arch.network/docs#core-architecture) [How Arch Works](https://book.arch.network/docs#how-arch-works) [πŸ›  Reference Documentation](https://book.arch.network/docs#-reference-documentation) [Need Help?](https://book.arch.network/docs#need-help) --- # Welcome to Arch Network Welcome to Arch Network ======================= A Bitcoin-native computation environment that enhances Bitcoin's capabilities through specialized virtual machine operations This documentation is actively maintained. If you find any issues or have suggestions for improvements, please visit our [GitHub repository](https://github.com/arch-network/docs) . [What is Arch Network?](https://book.arch.network/#what-is-arch-network) ------------------------------------------------------------------------- Arch Network is a computation environment that enhances Bitcoin's capabilities by enabling complex operations on Bitcoin UTXOs through its specialized virtual machine. Unlike Layer 2 solutions, Arch Network provides a native computation layer that works directly with Bitcoin's security model. [Choose Your Path πŸ‘‹](https://book.arch.network/#choose-your-path-) -------------------------------------------------------------------- [### πŸš€ Deploy First\ \ Get your first smart contract running on Arch Network as quickly as possible](https://book.arch.network/docs/quick-start/quick-start) [### πŸ—οΈ Run a Validator\ \ Set up and run your own validator node on the Arch Network](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) ### [Network Options](https://book.arch.network/#network-options) [### πŸ”§ Regtest\ \ Local development environment with instant block confirmation. Perfect for development and testing.](https://book.arch.network/docs/quick-start/quick-start) [### πŸ§ͺ Testnet\ \ Test network with real Bitcoin testnet integration. For testing in a live environment.](https://book.arch.network/docs/quick-start/quick-start) [Key Features](https://book.arch.network/#key-features) -------------------------------------------------------- [### Bitcoin-Native\ \ Direct integration with Bitcoin through UTXO management](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Computation Environment\ \ Execute complex programs within the Arch VM](https://book.arch.network/docs/setup-infrastructure/architecture) [### Program Development\ \ Write programs in Rust to interact with Bitcoin UTXOs](https://book.arch.network/docs/development/writing-your-first-program) [### Security\ \ Leverages Bitcoin's proven security guarantees through multi-signature validation](https://book.arch.network/docs/setup-infrastructure/network-architecture) [### Developer Tools\ \ Complete development environment with CLI tools and explorer](https://book.arch.network/docs/tools-apis/arch-cli-reference) [Prerequisites](https://book.arch.network/#prerequisites) ---------------------------------------------------------- Before you begin, ensure you have: * Node.js v19+ ([installation guide](https://book.arch.network/docs/quick-start/requirements) ) * Rust (latest stable) * Docker for local development * Basic understanding of [Bitcoin Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) [Core Architecture](https://book.arch.network/#core-architecture) ------------------------------------------------------------------ ### [How Arch Works](https://book.arch.network/#how-arch-works) Arch Network consists of three main components: 1. **Network Layer** * [Network Architecture](https://book.arch.network/docs/setup-infrastructure/network-architecture) * [Bootnode](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Network discovery and peer management * [Leader Node](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Transaction coordination * [Validator Nodes](https://book.arch.network/docs/setup-infrastructure/network-architecture) : Program execution 2. **Bitcoin Integration** * [UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Transaction tracking * State anchoring * Ownership validation * [RPC Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Bitcoin node communication * Transaction submission * Network synchronization 3. **Computation Layer** * [Programs](https://book.arch.network/docs/development/writing-your-first-program) * [Instructions](https://book.arch.network/docs/development/writing-your-first-program) * [Accounts](https://book.arch.network/docs/development/writing-your-first-program) * [System Calls](https://book.arch.network/docs/development/writing-your-first-program) * [Transaction Processing](https://book.arch.network/docs/tools-apis/sdk) * Message validation * State updates * UTXO management [πŸ›  Reference Documentation](https://book.arch.network/#-reference-documentation) ---------------------------------------------------------------------------------- [### API Reference\ \ RPC API Reference and Transaction Processing](https://book.arch.network/docs/tools-apis/api-reference) [### Program Examples\ \ Oracle Program and Fungible Token examples](https://book.arch.network/docs/development/writing-your-first-program) [### System Program\ \ Account Creation and Program Deployment](https://book.arch.network/docs/apl/introduction) [Need Help?](https://book.arch.network/#need-help) --------------------------------------------------- [### Join Discord\ \ Get support from the community](https://discord.gg/archnetwork) [### Architecture Overview\ \ Read the Architecture Overview](https://book.arch.network/docs/setup-infrastructure/architecture) [### Example Programs\ \ View Example Programs](https://book.arch.network/docs/development/writing-your-first-program) [### API Reference\ \ Check the API Reference](https://book.arch.network/docs/tools-apis/api-reference) πŸ’‘ **Pro Tip:** Use the search function (press 's' or '/' on your keyboard) to quickly find what you're looking for in the documentation. [Associated Token Account Program\ \ Complete guide to the APL Associated Token Account Program for deterministic token account management](https://book.arch.network/docs/apl/associated-token-account) ### On this page [What is Arch Network?](https://book.arch.network/#what-is-arch-network) [Choose Your Path πŸ‘‹](https://book.arch.network/#choose-your-path-) [Network Options](https://book.arch.network/#network-options) [Key Features](https://book.arch.network/#key-features) [Prerequisites](https://book.arch.network/#prerequisites) [Core Architecture](https://book.arch.network/#core-architecture) [How Arch Works](https://book.arch.network/#how-arch-works) [πŸ›  Reference Documentation](https://book.arch.network/#-reference-documentation) [Need Help?](https://book.arch.network/#need-help) --- # SDK Reference SDK Reference ============= [SDK Reference](https://book.arch.network/docs/sdk#sdk-reference) ================================================================== The Arch Network ecosystem provides two distinct SDKs for building applications. Each SDK serves different use cases and development environments. This page will help you choose the right SDK for your project. [Available SDKs](https://book.arch.network/docs/sdk#available-sdks) -------------------------------------------------------------------- ### [1\. TypeScript SDK (by Saturn)](https://book.arch.network/docs/sdk#1-typescript-sdk-by-saturn) The **TypeScript SDK** is developed and maintained by Saturn (@saturnbtc) and provides a comprehensive JavaScript/TypeScript interface for interacting with the Arch Network. **Package**: `@saturnbtcio/arch-sdk` **Repository**: [arch-typescript-sdk](https://github.com/saturnbtc/arch-typescript-sdk) **Language**: TypeScript/JavaScript **Best for**: * Frontend applications (React, Vue, Angular) * Node.js backend services * Web3 applications * Rapid prototyping * JavaScript/TypeScript developers ### [2\. Rust SDK](https://book.arch.network/docs/sdk#2-rust-sdk) The **Rust SDK** is the native SDK included in the main Arch Network repository. It provides low-level access to all network features and is used for building high-performance applications and programs. **Package**: `arch_sdk` **Repository**: Part of [arch-network](https://github.com/Arch-Network/arch-network) **Language**: Rust **Best for**: * On-chain programs (smart contracts) * High-performance applications * System-level integrations * Validator/node development * Rust developers [Choosing the Right SDK](https://book.arch.network/docs/sdk#choosing-the-right-sdk) ------------------------------------------------------------------------------------ ### [Use the TypeScript SDK when:](https://book.arch.network/docs/sdk#use-the-typescript-sdk-when) * Building web applications or dApps * Working with Node.js backends * Integrating Arch Network into existing JavaScript projects * You need quick development cycles * Your team is more familiar with JavaScript/TypeScript ### [Use the Rust SDK when:](https://book.arch.network/docs/sdk#use-the-rust-sdk-when) * Writing on-chain programs for Arch Network * Building high-performance applications * Developing system-level tools or validators * You need maximum control and efficiency * Your team is comfortable with Rust [Quick Start Comparison](https://book.arch.network/docs/sdk#quick-start-comparison) ------------------------------------------------------------------------------------ ### [TypeScript SDK Installation](https://book.arch.network/docs/sdk#typescript-sdk-installation) npm install @saturnbtcio/arch-sdk # or yarn add @saturnbtcio/arch-sdk ### [Rust SDK Installation](https://book.arch.network/docs/sdk#rust-sdk-installation) # In your Cargo.toml [dependencies] arch_sdk = "0.5.4" ### [Basic Connection Example](https://book.arch.network/docs/sdk#basic-connection-example) **TypeScript SDK:** import { Connection, Keypair } from '@saturnbtcio/arch-sdk'; const connection = new Connection('http://localhost:9002'); const keypair = Keypair.generate(); const isReady = await connection.isNodeReady(); console.log('Node ready:', isReady); **Rust SDK:** use arch_sdk::{Connection, Keypair}; #[tokio::main] async fn main() -> Result<(), Box> { let connection = Connection::new("http://localhost:9002"); let keypair = Keypair::new(); let is_ready = connection.is_node_ready().await?; println!("Node ready: {}", is_ready); Ok(()) } [Documentation Structure](https://book.arch.network/docs/sdk#documentation-structure) -------------------------------------------------------------------------------------- ### [TypeScript SDK Documentation](https://book.arch.network/docs/sdk#typescript-sdk-documentation) * [Getting Started with TypeScript SDK](https://book.arch.network/docs/typescript/getting-started.md) * [TypeScript API Reference](https://book.arch.network/docs/typescript/api-reference.md) * [TypeScript Examples](https://book.arch.network/docs/typescript/examples.md) * [Web3 Integration Guide](https://book.arch.network/docs/typescript/web3-integration.md) ### [Rust SDK Documentation](https://book.arch.network/docs/sdk#rust-sdk-documentation) * [Getting Started with Rust SDK](https://book.arch.network/docs/rust/getting-started.md) * [Rust API Reference](https://book.arch.network/docs/rust/api-reference.md) * [Program Development Guide](https://book.arch.network/docs/rust/program-development.md) * [Rust Examples](https://book.arch.network/docs/rust/examples.md) ### [Shared Concepts](https://book.arch.network/docs/sdk#shared-concepts) These concepts apply to both SDKs: * [Pubkey](https://book.arch.network/docs/pubkey.md) - Public key type for identifying accounts * [Account](https://book.arch.network/docs/account.md) - Account structure and management * [Instructions and Messages](https://book.arch.network/docs/instructions-and-messages.md) - Transaction building * [Runtime Transaction](https://book.arch.network/docs/runtime-transaction.md) - Transaction format * [Processed Transaction](https://book.arch.network/docs/processed-transaction.md) - Transaction results * [Signature](https://book.arch.network/docs/signature.md) - Digital signatures [Feature Comparison](https://book.arch.network/docs/sdk#feature-comparison) ---------------------------------------------------------------------------- | Feature | TypeScript SDK | Rust SDK | | --- | --- | --- | | Language | TypeScript/JavaScript | Rust | | Installation | npm/yarn | Cargo | | Async Support | Promises/async-await | Tokio async | | Program Development | Client-side only | Full support | | Browser Support | βœ… Full | ❌ No | | Node.js Support | βœ… Full | βœ… Full | | Performance | Good | Excellent | | Type Safety | TypeScript types | Rust type system | | Bundle Size | ~200KB | N/A | | Learning Curve | Moderate | Steep | [Migration Between SDKs](https://book.arch.network/docs/sdk#migration-between-sdks) ------------------------------------------------------------------------------------ While both SDKs interact with the same Arch Network, they have different APIs and patterns. Here are key differences to consider: ### [Connection Management](https://book.arch.network/docs/sdk#connection-management) * **TypeScript**: Uses promise-based async patterns * **Rust**: Uses Tokio-based async runtime ### [Error Handling](https://book.arch.network/docs/sdk#error-handling) * **TypeScript**: Try-catch with custom error types * **Rust**: Result pattern with detailed error types ### [Data Serialization](https://book.arch.network/docs/sdk#data-serialization) * **TypeScript**: JSON and Buffer-based serialization * **Rust**: Borsh and custom serialization [Getting Help](https://book.arch.network/docs/sdk#getting-help) ---------------------------------------------------------------- ### [TypeScript SDK Support](https://book.arch.network/docs/sdk#typescript-sdk-support) * **Issues**: [Saturn SDK GitHub Issues](https://github.com/saturnbtc/arch-typescript-sdk/issues) * **Documentation**: [TypeScript SDK Docs](https://book.arch.network/docs/typescript/getting-started.md) * **Examples**: [TypeScript Examples](https://github.com/saturnbtc/arch-typescript-sdk/tree/main/examples) ### [Rust SDK Support](https://book.arch.network/docs/sdk#rust-sdk-support) * **Issues**: [Arch Network GitHub Issues](https://github.com/arch-network/arch-network/issues) * **Documentation**: [Rust SDK Docs](https://book.arch.network/docs/rust/getting-started.md) * **Examples**: [Rust Examples](https://github.com/arch-network/arch-network/examples) ### [General Support](https://book.arch.network/docs/sdk#general-support) * **Discord**: [Arch Network Discord](https://discord.gg/archnetwork) * **Forum**: [Arch Network Forum](https://forum.arch.network/) * **Stack Overflow**: Tag with `arch-network` [Next Steps](https://book.arch.network/docs/sdk#next-steps) ------------------------------------------------------------ Choose your SDK and get started: * **[Get Started with TypeScript SDK β†’](https://book.arch.network/docs/typescript/getting-started.md) ** * **[Get Started with Rust SDK β†’](https://book.arch.network/docs/rust/getting-started.md) ** For a general introduction to Arch Network concepts, visit our [Getting Started Guide](https://book.arch.network/docs/quick-start/quick-start) . [RPC Reference\ \ Previous Page](https://book.arch.network/docs/reference/rpc) [Getting Started with the TypeScript SDK\ \ Next Page](https://book.arch.network/docs/sdk/typescript/getting-started) ### On this page [SDK Reference](https://book.arch.network/docs/sdk#sdk-reference) [Available SDKs](https://book.arch.network/docs/sdk#available-sdks) [1\. TypeScript SDK (by Saturn)](https://book.arch.network/docs/sdk#1-typescript-sdk-by-saturn) [2\. Rust SDK](https://book.arch.network/docs/sdk#2-rust-sdk) [Choosing the Right SDK](https://book.arch.network/docs/sdk#choosing-the-right-sdk) [Use the TypeScript SDK when:](https://book.arch.network/docs/sdk#use-the-typescript-sdk-when) [Use the Rust SDK when:](https://book.arch.network/docs/sdk#use-the-rust-sdk-when) [Quick Start Comparison](https://book.arch.network/docs/sdk#quick-start-comparison) [TypeScript SDK Installation](https://book.arch.network/docs/sdk#typescript-sdk-installation) [Rust SDK Installation](https://book.arch.network/docs/sdk#rust-sdk-installation) [Basic Connection Example](https://book.arch.network/docs/sdk#basic-connection-example) [Documentation Structure](https://book.arch.network/docs/sdk#documentation-structure) [TypeScript SDK Documentation](https://book.arch.network/docs/sdk#typescript-sdk-documentation) [Rust SDK Documentation](https://book.arch.network/docs/sdk#rust-sdk-documentation) [Shared Concepts](https://book.arch.network/docs/sdk#shared-concepts) [Feature Comparison](https://book.arch.network/docs/sdk#feature-comparison) [Migration Between SDKs](https://book.arch.network/docs/sdk#migration-between-sdks) [Connection Management](https://book.arch.network/docs/sdk#connection-management) [Error Handling](https://book.arch.network/docs/sdk#error-handling) [Data Serialization](https://book.arch.network/docs/sdk#data-serialization) [Getting Help](https://book.arch.network/docs/sdk#getting-help) [TypeScript SDK Support](https://book.arch.network/docs/sdk#typescript-sdk-support) [Rust SDK Support](https://book.arch.network/docs/sdk#rust-sdk-support) [General Support](https://book.arch.network/docs/sdk#general-support) [Next Steps](https://book.arch.network/docs/sdk#next-steps) --- # πŸš€ Quick Start Guide Quick Start πŸš€ Quick Start Guide ==================== Get your first program running on Arch Network in under 15 minutes Welcome to Arch Network! Let's get your first program running in under 15 minutes. [Prerequisites](https://book.arch.network/docs/quick-start/quick-start#prerequisites) -------------------------------------------------------------------------------------- Before starting, ensure you have the following tools installed: * **Git** (v2.0 or later) * **Rust** (v1.84.1 or later) - [Install Rust](https://rustup.rs/) * **Solana CLI** (v2.2.14 or later) - [Install Solana](https://docs.solana.com/cli/install-solana-cli-tools) * **Arch Network CLI** - Download from [Arch Network Releases](https://github.com/Arch-Network/arch-node/releases/latest) * **Docker** - Required for local development - [Install Docker](https://docs.docker.com/engine/install/) **Important**: Arch Network now requires Solana CLI 2.x. Please ensure you have version 2.2.14 or later installed. Verify your installation: git --version rustc --version solana --version # Should show 2.2.14 or later arch-cli --version docker --version If you encounter any issues during installation, join our [Discord](https://discord.gg/archnetwork) for support. [πŸš€ Quick Start Project](https://book.arch.network/docs/quick-start/quick-start#-quick-start-project) ------------------------------------------------------------------------------------------------------ ### [1\. Clone Example Project](https://book.arch.network/docs/quick-start/quick-start#1-clone-example-project) # Get the starter example git clone https://github.com/Arch-Network/arch-examples cd arch-examples/examples/helloworld ### [2\. Start Local Development Environment](https://book.arch.network/docs/quick-start/quick-start#2-start-local-development-environment) Choose one of the following network modes: #### [Option A: Local Development (Recommended)](https://book.arch.network/docs/quick-start/quick-start#option-a-local-development-recommended) **Prerequisites:** * **Docker**: Required on all platforms * **Docker Management** (optional but recommended): * **macOS**: [OrbStack](https://orbstack.dev/) (recommended) or [Docker Desktop](https://www.docker.com/products/docker-desktop/) * **Linux**: [Docker Desktop](https://www.docker.com/products/docker-desktop/) (optional GUI) # Use the orchestrate command for full local devnet arch-cli orchestrate start This starts a complete local development environment with: * Bitcoin Core (regtest mode) * Titan indexer * Local validator **Advanced Options:** # Use local source code for development arch-cli orchestrate start --local "$(pwd)" # Skip bitcoind and use remote Bitcoin RPC arch-cli orchestrate start --no-bitcoind # Force rebuild images arch-cli orchestrate start --force-rebuild #### [Option B: Testnet (Remote Bitcoin + Local Arch)](https://book.arch.network/docs/quick-start/quick-start#option-b-testnet-remote-bitcoin--local-arch) For testnet development with remote Bitcoin node: # 1. Create a configuration profile arch-cli config create-profile testnet \ --bitcoin-node-endpoint http://bitcoin-rpc.test.arch.network:80 \ --bitcoin-node-username bitcoin \ --bitcoin-node-password 0F_Ed53o4kR7nxh3xNaSQx-2M3TY16L55mz5y9fjdrk \ --bitcoin-network testnet \ --arch-node-url http://localhost:9002 # 2. Start local Arch environment (no local bitcoind) arch-cli --profile testnet orchestrate start --local "$(pwd)" --no-bitcoind #### [Option C: Devnet (Full Local Stack)](https://book.arch.network/docs/quick-start/quick-start#option-c-devnet-full-local-stack) For devnet, you'll need to run your own Bitcoin regtest node and Titan indexer: # 1. Start Bitcoin Core in regtest mode bitcoind -regtest -port=18444 -rpcport=18443 \ -rpcuser=bitcoin -rpcpassword=bitcoinpass \ -fallbackfee=0.001 # 2. First-time setup (only needed once) # Create a wallet called "testwallet" bitcoin-cli -regtest -rpcuser=bitcoin -rpcpassword=bitcoinpass createwallet testwallet # Generate an address and mine the first 100 blocks to it ADDRESS=$(bitcoin-cli -regtest -rpcuser=bitcoin -rpcpassword=bitcoinpass getnewaddress) bitcoin-cli -regtest -rpcuser=bitcoin -rpcpassword=bitcoinpass generatetoaddress 100 $ADDRESS # 3. Clone and build Titan indexer (if not already done) git clone https://github.com/saturnbtc/Titan.git cd Titan cargo build --release cd .. # 4. Start Titan indexer ./Titan/target/release/titan \ --network regtest \ --bitcoin-rpc-url http://bitcoin:bitcoinpass@127.0.0.1:18443 \ --http-addr 127.0.0.1:8080 \ --tcp-addr 127.0.0.1:3030 # 5. Start local validator arch-cli orchestrate validator-start ### [3\. Verify Your Environment](https://book.arch.network/docs/quick-start/quick-start#3-verify-your-environment) Check that all services are running: # Check orchestrated services status arch-cli orchestrate validator-status # Check network connectivity arch-cli get-block-height # Check Bitcoin integration arch-cli orchestrate mine-blocks --num-blocks 1 ### [4\. Build and Deploy Your Program](https://book.arch.network/docs/quick-start/quick-start#4-build-and-deploy-your-program) # Build the example program cargo build-sbf # Deploy to your local network arch-cli deploy target/deploy/ ### [5\. Test Your Program](https://book.arch.network/docs/quick-start/quick-start#5-test-your-program) # Check the deployed program arch-cli show # Run the program (if it has a client) cargo run [🎯 Next Steps](https://book.arch.network/docs/quick-start/quick-start#-next-steps) ------------------------------------------------------------------------------------ [### Learn More\ \ Check out our Program Development Guide](https://book.arch.network/docs/development/writing-your-first-program) [### Token Development\ \ Explore APL Token Creation](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### Examples\ \ Browse more examples in the examples directory](https://github.com/Arch-Network/arch-examples) [### Community\ \ Join our Discord for support and updates](https://discord.gg/archnetwork) [πŸ”§ Troubleshooting](https://book.arch.network/docs/quick-start/quick-start#-troubleshooting) ---------------------------------------------------------------------------------------------- ### [Common Issues](https://book.arch.network/docs/quick-start/quick-start#common-issues) **Docker not running:** # Check Docker status docker ps # Start Docker if needed # macOS: Open Docker Desktop or OrbStack # Linux: sudo systemctl start docker **Port conflicts:** # Check if ports are in use netstat -an | grep 9002 netstat -an | grep 18443 # Stop conflicting services or use different ports **Build failures:** # Clean and rebuild cargo clean cargo build-sbf # Check Rust version rustc --version # Should be 1.84.1+ **Validator won't start:** # Reset environment arch-cli orchestrate reset # Check logs arch-cli orchestrate validator-status ### [Getting Help](https://book.arch.network/docs/quick-start/quick-start#getting-help) [### Discord\ \ Get support from the community](https://discord.gg/archnetwork) [### GitHub Issues\ \ Report bugs and request features](https://github.com/Arch-Network/arch-node/issues) [### Documentation\ \ Browse the full documentation](https://docs.arch.network/) * * * **Congratulations!** You've successfully set up your Arch Network development environment. You're now ready to build and deploy programs on the most Bitcoin-native smart contract platform. [Syscalls\ \ Previous Page](https://book.arch.network/docs/program/syscall) [System Requirements\ \ Hardware and software requirements for Arch Network development](https://book.arch.network/docs/quick-start/requirements) ### On this page [Prerequisites](https://book.arch.network/docs/quick-start/quick-start#prerequisites) [πŸš€ Quick Start Project](https://book.arch.network/docs/quick-start/quick-start#-quick-start-project) [1\. Clone Example Project](https://book.arch.network/docs/quick-start/quick-start#1-clone-example-project) [2\. Start Local Development Environment](https://book.arch.network/docs/quick-start/quick-start#2-start-local-development-environment) [Option A: Local Development (Recommended)](https://book.arch.network/docs/quick-start/quick-start#option-a-local-development-recommended) [Option B: Testnet (Remote Bitcoin + Local Arch)](https://book.arch.network/docs/quick-start/quick-start#option-b-testnet-remote-bitcoin--local-arch) [Option C: Devnet (Full Local Stack)](https://book.arch.network/docs/quick-start/quick-start#option-c-devnet-full-local-stack) [3\. Verify Your Environment](https://book.arch.network/docs/quick-start/quick-start#3-verify-your-environment) [4\. Build and Deploy Your Program](https://book.arch.network/docs/quick-start/quick-start#4-build-and-deploy-your-program) [5\. Test Your Program](https://book.arch.network/docs/quick-start/quick-start#5-test-your-program) [🎯 Next Steps](https://book.arch.network/docs/quick-start/quick-start#-next-steps) [πŸ”§ Troubleshooting](https://book.arch.network/docs/quick-start/quick-start#-troubleshooting) [Common Issues](https://book.arch.network/docs/quick-start/quick-start#common-issues) [Getting Help](https://book.arch.network/docs/quick-start/quick-start#getting-help) --- # πŸ—οΈ Validator Setup Setup Infrastructure πŸ—οΈ Validator Setup =================== Complete guide to setting up a full Arch Network validator node with Bitcoin Core and Titan indexer Welcome to the validator setup guide! This guide will walk you through setting up a full Arch Network validator node. You can choose between an automated setup or manual configuration depending on your needs. [🎯 What You'll Build](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-what-youll-build) ---------------------------------------------------------------------------------------------------------------------- [🎯 Component Architecture](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-component-architecture) --------------------------------------------------------------------------------------------------------------------------------- [πŸ’‘ Understanding Your Role](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-understanding-your-role) ----------------------------------------------------------------------------------------------------------------------------------- As a validator, you will: * Execute smart contracts and validate transactions * Participate in network consensus * Help secure the Bitcoin integration * Earn rewards for your contribution [πŸ“‹ System Requirements](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-system-requirements) --------------------------------------------------------------------------------------------------------------------------- * **CPU**: 4+ cores recommended * **RAM**: 16GB+ recommended * **Storage**: 100GB+ SSD for regtest, 500GB+ for testnet/mainnet * **Network**: Stable internet connection (10+ Mbps) * **OS**: Linux (Ubuntu 20.04+) or macOS (12.0+) [πŸš€ Setup Options](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-setup-options) --------------------------------------------------------------------------------------------------------------- Choose your preferred setup method: ### [Option A: Automated Setup (Recommended)](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#option-a-automated-setup-recommended) The easiest way to get started using the CLI orchestrate command. **Prerequisites:** * **Docker**: Required on all platforms - [Install Docker](https://docs.docker.com/engine/install/) * **Docker Management** (optional but recommended): * **macOS**: [OrbStack](https://orbstack.dev/) (recommended) or [Docker Desktop](https://www.docker.com/products/docker-desktop/) * **Linux**: [Docker Desktop](https://www.docker.com/products/docker-desktop/) (optional GUI) * **Arch Network CLI** - Download from [releases](https://github.com/Arch-Network/arch-node/releases/latest) **Setup:** # 1. Download and install the Arch CLI # (Download the appropriate binary for your platform from the releases page) # 2. Start the complete validator stack arch-cli orchestrate start This automatically starts: * Bitcoin Core (regtest mode) * Titan indexer * Local validator * All necessary networking and configuration **Service URLs:** * Bitcoin Core RPC: `http://127.0.0.1:18443` * Titan API: `http://127.0.0.1:3030` * Validator RPC: `http://127.0.0.1:9002` **Management Commands:** # Stop all services arch-cli orchestrate stop # Restart all services arch-cli orchestrate restart # Check service status arch-cli orchestrate status # View logs arch-cli orchestrate logs # Reset everything (clears all data) arch-cli orchestrate reset ### [Option B: Manual Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#option-b-manual-setup) For advanced users who want full control over each component. #### [Step 1: Bitcoin Core Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-1-bitcoin-core-setup) **Install Bitcoin Core:** # Download and install Bitcoin Core # Visit https://bitcoincore.org/en/download/ for your platform # For Ubuntu/Debian: wget https://bitcoincore.org/bin/bitcoin-core-25.0/bitcoin-25.0-x86_64-linux-gnu.tar.gz tar -xzf bitcoin-25.0-x86_64-linux-gnu.tar.gz sudo cp bitcoin-25.0/bin/* /usr/local/bin/ **Configure Bitcoin Core:** # Create Bitcoin data directory mkdir -p ~/.bitcoin # Create bitcoin.conf cat > ~/.bitcoin/bitcoin.conf << EOF # Network configuration regtest=1 server=1 rpcuser=bitcoin rpcpassword=bitcoinpass rpcport=18443 rpcbind=127.0.0.1 rpcallowip=127.0.0.1 # Performance settings dbcache=1000 maxmempool=2000 maxconnections=25 # Logging debug=1 logtimestamps=1 logips=1 EOF **Start Bitcoin Core:** # Start Bitcoin Core in regtest mode bitcoind -regtest -daemon # Verify it's running bitcoin-cli -regtest getblockchaininfo #### [Step 2: Titan Indexer Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-2-titan-indexer-setup) **Install Titan:** # Clone Titan repository git clone https://github.com/saturnbtc/Titan.git cd Titan # Build Titan cargo build --release # Create Titan configuration mkdir -p ~/.titan cat > ~/.titan/config.toml << EOF [network] network = "regtest" [bitcoin] rpc_url = "http://bitcoin:bitcoinpass@127.0.0.1:18443" [server] http_addr = "127.0.0.1:8080" tcp_addr = "127.0.0.1:3030" EOF **Start Titan:** # Start Titan indexer ./target/release/titan --config ~/.titan/config.toml #### [Step 3: Arch Validator Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-3-arch-validator-setup) **Install Arch Validator:** # Download Arch validator binary # Visit https://github.com/Arch-Network/arch-node/releases/latest # For Linux: wget https://github.com/Arch-Network/arch-node/releases/latest/download/arch-node-x86_64-unknown-linux-gnu chmod +x arch-node-x86_64-unknown-linux-gnu sudo mv arch-node-x86_64-unknown-linux-gnu /usr/local/bin/arch-node **Configure Validator:** # Create validator data directory mkdir -p ~/.arch_data # Create validator configuration cat > ~/.arch_data/config.toml << EOF [network] mode = "devnet" bitcoin_rpc_url = "http://bitcoin:bitcoinpass@127.0.0.1:18443" titan_rpc_url = "http://127.0.0.1:3030" [validator] rpc_port = 9002 p2p_port = 9003 data_dir = "~/.arch_data" [logging] level = "info" EOF **Start Validator:** # Start Arch validator arch-node --config ~/.arch_data/config.toml [πŸ”§ Configuration Options](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-configuration-options) ------------------------------------------------------------------------------------------------------------------------------- ### [Network Modes](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#network-modes) [### Regtest (Development)\ \ Local development with instant block generation](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#regtest-configuration) [### Testnet (Testing)\ \ Public test network with real Bitcoin testnet](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#testnet-configuration) [### Mainnet (Production)\ \ Production network (not yet available)](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#mainnet-configuration) ### [Regtest Configuration](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#regtest-configuration) Perfect for development and testing: # Bitcoin Core regtest configuration regtest=1 server=1 rpcuser=bitcoin rpcpassword=bitcoinpass rpcport=18443 # Generate blocks instantly for testing bitcoin-cli -regtest generatetoaddress 100 $(bitcoin-cli -regtest getnewaddress) ### [Testnet Configuration](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#testnet-configuration) For testing with real Bitcoin testnet: # Bitcoin Core testnet configuration testnet=1 server=1 rpcuser=bitcoin rpcpassword=bitcoinpass rpcport=18332 # Connect to testnet bitcoin-cli -testnet getblockchaininfo [πŸ§ͺ Testing Your Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-testing-your-setup) ------------------------------------------------------------------------------------------------------------------------- ### [Verify Bitcoin Core](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-bitcoin-core) # Check Bitcoin Core status bitcoin-cli -regtest getblockchaininfo # Generate some test blocks bitcoin-cli -regtest generatetoaddress 10 $(bitcoin-cli -regtest getnewaddress) # Check balance bitcoin-cli -regtest getbalance ### [Verify Titan Indexer](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-titan-indexer) # Check Titan API curl http://127.0.0.1:8080/health # Get block information curl http://127.0.0.1:8080/api/v1/blocks/latest ### [Verify Arch Validator](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-arch-validator) # Check validator status curl http://127.0.0.1:9002/health # Get network information curl http://127.0.0.1:9002/api/v1/network/info [🚨 Troubleshooting](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-troubleshooting) ------------------------------------------------------------------------------------------------------------------- ### [Common Issues](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#common-issues) **Bitcoin Core won't start:** # Check if port is already in use netstat -tulpn | grep 18443 # Kill existing process pkill bitcoind # Check Bitcoin Core logs tail -f ~/.bitcoin/regtest/debug.log **Titan connection issues:** # Verify Bitcoin RPC connection curl -u bitcoin:bitcoinpass http://127.0.0.1:18443 # Check Titan logs tail -f ~/.titan/logs/titan.log **Validator startup problems:** # Check validator logs tail -f ~/.arch_data/logs/validator.log # Verify all dependencies are running arch-cli orchestrate status ### [Performance Optimization](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#performance-optimization) **For better performance:** # Increase Bitcoin Core cache echo "dbcache=2000" >> ~/.bitcoin/bitcoin.conf # Optimize Titan settings echo "max_connections=100" >> ~/.titan/config.toml # Restart services arch-cli orchestrate restart [πŸ“š Next Steps](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-next-steps) --------------------------------------------------------------------------------------------------------- [### Deploy Your First Program\ \ Learn how to deploy and interact with programs](https://book.arch.network/docs/development/writing-your-first-program) [### Understanding Architecture\ \ Deep dive into Arch Network architecture](https://book.arch.network/docs/setup-infrastructure/architecture) [### Bitcoin Integration\ \ Learn how Arch integrates with Bitcoin](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Join the Community\ \ Get help and connect with other developers](https://discord.gg/archnetwork) [πŸ†˜ Getting Help](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-getting-help) ------------------------------------------------------------------------------------------------------------- If you encounter issues: 1. **Check the logs** for error messages 2. **Verify all services** are running correctly 3. **Join our Discord** for community support 4. **Review the troubleshooting guide** for common solutions 5. **Submit an issue** on GitHub if you find a bug Welcome to the Arch Network validator community! πŸŽ‰ [Architecture Overview\ \ Understanding the core components and architecture of Arch Network](https://book.arch.network/docs/setup-infrastructure/architecture) [Network Architecture\ \ Understanding Arch Network's distributed system architecture and node interactions](https://book.arch.network/docs/setup-infrastructure/network-architecture) ### On this page [🎯 What You'll Build](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-what-youll-build) [🎯 Component Architecture](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-component-architecture) [πŸ’‘ Understanding Your Role](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-understanding-your-role) [πŸ“‹ System Requirements](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-system-requirements) [πŸš€ Setup Options](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-setup-options) [Option A: Automated Setup (Recommended)](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#option-a-automated-setup-recommended) [Option B: Manual Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#option-b-manual-setup) [Step 1: Bitcoin Core Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-1-bitcoin-core-setup) [Step 2: Titan Indexer Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-2-titan-indexer-setup) [Step 3: Arch Validator Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#step-3-arch-validator-setup) [πŸ”§ Configuration Options](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-configuration-options) [Network Modes](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#network-modes) [Regtest Configuration](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#regtest-configuration) [Testnet Configuration](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#testnet-configuration) [πŸ§ͺ Testing Your Setup](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-testing-your-setup) [Verify Bitcoin Core](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-bitcoin-core) [Verify Titan Indexer](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-titan-indexer) [Verify Arch Validator](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#verify-arch-validator) [🚨 Troubleshooting](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-troubleshooting) [Common Issues](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#common-issues) [Performance Optimization](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#performance-optimization) [πŸ“š Next Steps](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-next-steps) [πŸ†˜ Getting Help](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup#-getting-help) --- # Bitcoin Integration Core Concepts Bitcoin Integration =================== How Arch Network integrates with Bitcoin through UTXO management and RPC interfaces Arch Network provides direct integration with Bitcoin, enabling programs to interact with Bitcoin's UTXO model while maintaining Bitcoin's security guarantees. This document details how Arch Network integrates with Bitcoin. [Architecture Overview](https://book.arch.network/docs/core-concepts/bitcoin-integration#architecture-overview) ---------------------------------------------------------------------------------------------------------------- **Diagram components** * **Bitcoin Network (Bitcoin Node)**: Canonical source of blocks, transactions, and UTXOs; all confirmations and proofs ultimately derive from it. * **Titan Client**: Bridges the Bitcoin node and Arch leader by streaming headers, transactions, and UTXO proofs so the leader maintains an up‑to‑date Bitcoin view. * **Leader Node (Bitcoin Integration)**: Orchestrates verification and submission of Bitcoin‑related operations, coordinating validation and finalization across the network. * **Validator Network (Programs)**: Executes programs and participates in consensus; validators verify state transitions and provide threshold signatures for Bitcoin‑anchored actions. [Core Components](https://book.arch.network/docs/core-concepts/bitcoin-integration#core-components) ---------------------------------------------------------------------------------------------------- ### [1\. UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-management) Arch Network manages Bitcoin UTXOs through a specialized system: **Diagram components** * **TransactionID & OutputIndex**: Together identify a specific Bitcoin UTXO; they select the exact output being referenced. * **UtxoMeta**: Arch‑side record of the UTXO (txid, vout, amount, script, confirmations) used for ownership, spend checks, and proof verification. * **ProgramState**: Program‑maintained state linked to UTXOs; updates when UTXOs are created or spent to reflect application logic. // UTXO Metadata Structure pub struct UtxoMeta { pub txid: [u8; 32], // Transaction ID pub vout: u32, // Output index pub amount: u64, // Amount in satoshis pub script_pubkey: Vec, // Output script pub confirmation_height: Option, // Block height of confirmation } // UTXO Account State pub struct UtxoAccount { pub meta: UtxoMeta, pub owner: Pubkey, pub delegate: Option, pub state: Vec, pub is_frozen: bool, } Key operations: // UTXO Operations pub trait UtxoOperations { fn create_utxo(meta: UtxoMeta, owner: &Pubkey) -> Result<()>; fn spend_utxo(utxo: &UtxoMeta, signature: &Signature) -> Result<()>; fn freeze_utxo(utxo: &UtxoMeta, authority: &Pubkey) -> Result<()>; fn delegate_utxo(utxo: &UtxoMeta, delegate: &Pubkey) -> Result<()>; } ### [2\. Bitcoin RPC Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-bitcoin-rpc-integration) **Diagram components** * **Arch Program**: Issues reads and submissions related to Bitcoin state and transactions as part of program execution. * **Bitcoin RPC Interface**: Authenticates and routes requests to the configured Bitcoin node, applying timeouts and network settings from configuration. * **Bitcoin Node**: Serves chain data and accepts transaction broadcasts; its view anchors program interactions to Bitcoin consensus. * **Configuration**: Endpoint, credentials, wallet, network, and timeouts that control RPC behavior and security boundaries. * **Bitcoin Network**: The broader peer‑to‑peer network the node participates in, providing consensus and propagation for transactions and blocks. Programs can interact with Bitcoin through RPC calls: // Bitcoin RPC Configuration pub struct BitcoinRpcConfig { pub endpoint: String, pub port: u16, pub username: String, pub password: String, pub wallet: Option, pub network: BitcoinNetwork, pub timeout: Duration, } // RPC Interface pub trait BitcoinRpc { fn get_block_count(&self) -> Result; fn get_block_hash(&self, height: u64) -> Result; fn get_transaction(&self, txid: &Txid) -> Result; fn send_raw_transaction(&self, tx: &[u8]) -> Result; fn verify_utxo(&self, utxo: &UtxoMeta) -> Result; } [Transaction Flow](https://book.arch.network/docs/core-concepts/bitcoin-integration#transaction-flow) ------------------------------------------------------------------------------------------------------ **Diagram components** * **Program**: Constructs intents and requests UTXO creation or spending based on application logic. * **Leader**: Validates requests, aggregates threshold signatures, and submits the finalized transaction to Bitcoin. * **Validator**: Independently verifies inputs/outputs and signs if rules are satisfied, contributing to threshold signing. * **Bitcoin**: Confirms the transaction on‑chain and provides observable finality that programs can rely on. ### [1\. Transaction Creation](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-transaction-creation) // Create new UTXO transaction pub struct UtxoCreation { pub amount: u64, pub owner: Pubkey, pub metadata: Option>, } impl UtxoCreation { pub fn new(amount: u64, owner: Pubkey) -> Self { Self { amount, owner, metadata: None, } } pub fn with_metadata(mut self, metadata: Vec) -> Self { self.metadata = Some(metadata); self } } ### [2\. Transaction Validation](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-validation) // Validation rules pub trait TransactionValidation { fn validate_inputs(&self, tx: &Transaction) -> Result<()>; fn validate_outputs(&self, tx: &Transaction) -> Result<()>; fn validate_signatures(&self, tx: &Transaction) -> Result<()>; fn validate_script(&self, tx: &Transaction) -> Result<()>; } ### [3\. State Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-state-management) // State transition pub struct StateTransition { pub previous_state: Hash, pub next_state: Hash, pub utxos_created: Vec, pub utxos_spent: Vec, pub bitcoin_height: u64, } [Security Model](https://book.arch.network/docs/core-concepts/bitcoin-integration#security-model) -------------------------------------------------------------------------------------------------- ### [1\. UTXO Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-security) * Ownership verification through public key cryptography * Double-spend prevention through UTXO consumption * State anchoring to Bitcoin transactions * Threshold signature requirements ### [2\. Transaction Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-security) // Transaction security parameters pub struct SecurityParams { pub min_confirmations: u32, pub signature_threshold: u32, pub timelock_blocks: u32, pub max_witness_size: usize, } ### [3\. Network Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-network-security) * Multi-signature validation * Threshold signing (t-of-n) * Bitcoin-based finality * Cross-validator consistency [Error Handling](https://book.arch.network/docs/core-concepts/bitcoin-integration#error-handling) -------------------------------------------------------------------------------------------------- ### [1\. Bitcoin Errors](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-bitcoin-errors) pub enum BitcoinError { ConnectionFailed(String), InvalidTransaction(String), InsufficientFunds(u64), InvalidUtxo(UtxoMeta), RpcError(String), } ### [2\. UTXO Errors](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-utxo-errors) pub enum UtxoError { NotFound(UtxoMeta), AlreadySpent(UtxoMeta), InvalidOwner(Pubkey), InvalidSignature(Signature), InvalidState(Hash), } [Best Practices](https://book.arch.network/docs/core-concepts/bitcoin-integration#best-practices) -------------------------------------------------------------------------------------------------- ### [1\. UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-management-1) * Always verify UTXO ownership * Wait for sufficient confirmations * Handle reorganizations gracefully * Implement proper error handling ### [2\. Transaction Processing](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-processing) * Validate all inputs and outputs * Check signature thresholds * Maintain proper state transitions * Monitor Bitcoin network status ### [3\. Security Considerations](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-security-considerations) * Protect private keys * Validate all signatures * Monitor for double-spend attempts * Handle network partitions [APL Token Program\ \ Complete reference for the Arch Program Library Token Program - creating and managing fungible tokens](https://book.arch.network/docs/apl/token-program) [ROAST and FROST Consensus\ \ Arch's consensus mechanism combining ROAST and FROST for secure, efficient distributed consensus](https://book.arch.network/docs/core-concepts/consensus) ### On this page [Architecture Overview](https://book.arch.network/docs/core-concepts/bitcoin-integration#architecture-overview) [Core Components](https://book.arch.network/docs/core-concepts/bitcoin-integration#core-components) [1\. UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-management) [2\. Bitcoin RPC Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-bitcoin-rpc-integration) [Transaction Flow](https://book.arch.network/docs/core-concepts/bitcoin-integration#transaction-flow) [1\. Transaction Creation](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-transaction-creation) [2\. Transaction Validation](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-validation) [3\. State Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-state-management) [Security Model](https://book.arch.network/docs/core-concepts/bitcoin-integration#security-model) [1\. UTXO Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-security) [2\. Transaction Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-security) [3\. Network Security](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-network-security) [Error Handling](https://book.arch.network/docs/core-concepts/bitcoin-integration#error-handling) [1\. Bitcoin Errors](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-bitcoin-errors) [2\. UTXO Errors](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-utxo-errors) [Best Practices](https://book.arch.network/docs/core-concepts/bitcoin-integration#best-practices) [1\. UTXO Management](https://book.arch.network/docs/core-concepts/bitcoin-integration#1-utxo-management-1) [2\. Transaction Processing](https://book.arch.network/docs/core-concepts/bitcoin-integration#2-transaction-processing) [3\. Security Considerations](https://book.arch.network/docs/core-concepts/bitcoin-integration#3-security-considerations) --- # Architecture Overview Setup Infrastructure Architecture Overview ===================== Understanding the core components and architecture of Arch Network [Core Components](https://book.arch.network/docs/setup-infrastructure/architecture#core-components) ---------------------------------------------------------------------------------------------------- ### [Arch VM](https://book.arch.network/docs/setup-infrastructure/architecture#arch-vm) The Arch Virtual Machine (VM) is built on eBPF technology, providing a secure and efficient environment for executing programs. Key features: * πŸ”„ Manages program execution * ⚑ Handles state transitions * 🎯 Ensures deterministic computation * πŸ”— Provides syscalls for Bitcoin UTXO operations * πŸ’° Supports compute budget management * 🎭 Handles program upgrades and migrations ### [Bitcoin Integration](https://book.arch.network/docs/setup-infrastructure/architecture#bitcoin-integration) Arch Network interacts directly with Bitcoin through: * πŸ’Ό Native UTXO management via `bitcoin-internal` crate * βœ… Transaction validation and synchronization * πŸ” Multi-signature coordination * πŸ“ State commitment to Bitcoin * πŸ”„ Real-time Bitcoin network monitoring * πŸ“Š UTXO graph processing and rollback support ### [Distributed Key Generation (DKG)](https://book.arch.network/docs/setup-infrastructure/architecture#distributed-key-generation-dkg) The DKG system enables secure multi-signature operations: * πŸ”‘ Threshold signature schemes (t-of-n) * 🌐 Peer-to-peer key generation * πŸ”„ Dynamic participant management * πŸ›‘οΈ Malicious participant detection * πŸ“‘ Network message routing and validation ### [Validator Network](https://book.arch.network/docs/setup-infrastructure/architecture#validator-network) The validator network consists of multiple node types that work together: #### [Node Types](https://book.arch.network/docs/setup-infrastructure/architecture#node-types) | Node Type | Primary Responsibilities | | --- | --- | | **Leader Node** | β€’ Coordinates transaction signing
β€’ Submits signed transactions to Bitcoin
β€’ Manages validator communication
β€’ Orchestrates DKG sessions | | **Validator Nodes** | β€’ Execute programs in the Arch VM
β€’ Validate transactions
β€’ Participate in multi-signature operations
β€’ Maintain network state
β€’ Contribute to DKG operations | | **Bootnode** | β€’ Handles initial network discovery
β€’ Similar to Bitcoin DNS seeds
β€’ Helps new nodes join the network
β€’ Manages peer information distribution | ### [Core Programs](https://book.arch.network/docs/setup-infrastructure/architecture#core-programs) Arch Network includes several built-in programs that provide essential functionality: #### [APL Token Program](https://book.arch.network/docs/setup-infrastructure/architecture#apl-token-program) * πŸͺ™ Fungible token creation and management * πŸ” Multi-signature support * ❄️ Account freezing and thawing * πŸ“Š Supply management and minting * 🎭 Authority management and delegation #### [Associated Token Account (ATA)](https://book.arch.network/docs/setup-infrastructure/architecture#associated-token-account-ata) * πŸ”— Automatic token account creation * πŸ’° Rent-exempt account management * 🎯 Deterministic address derivation * πŸ”„ Account lifecycle management #### [Compute Budget Program](https://book.arch.network/docs/setup-infrastructure/architecture#compute-budget-program) * ⚑ Transaction compute unit management * πŸ’° Fee calculation and optimization * 🎯 Resource allocation control * πŸ“Š Performance monitoring #### [System Program](https://book.arch.network/docs/setup-infrastructure/architecture#system-program) * πŸ—οΈ Account creation and management * πŸ”„ Ownership transfers * πŸ’° Lamport management * πŸ”— UTXO anchoring [Transaction Flow](https://book.arch.network/docs/setup-infrastructure/architecture#transaction-flow) ------------------------------------------------------------------------------------------------------ [Security Model](https://book.arch.network/docs/setup-infrastructure/architecture#security-model) -------------------------------------------------------------------------------------------------- Arch Network implements a robust multi-layered security model that directly leverages Bitcoin's security guarantees: ### [1\. UTXO Security](https://book.arch.network/docs/setup-infrastructure/architecture#1-utxo-security) * πŸ”’ **Ownership Verification** * Public key cryptography using secp256k1 * BIP322 message signing for secure ownership proofs * Double-spend prevention through UTXO consumption tracking * πŸ”— **State Management** * State anchoring to Bitcoin transactions * Atomic state transitions with rollback capability * Cross-validator state consistency checks * Real-time UTXO graph validation ### [2\. Transaction Security](https://book.arch.network/docs/setup-infrastructure/architecture#2-transaction-security) pub struct SecurityParams { pub min_confirmations: u32, // Required Bitcoin confirmations pub signature_threshold: u32, // Multi-sig threshold pub timelock_blocks: u32, // Timelock requirement pub max_witness_size: usize, // Maximum witness data size pub dkg_timeout: Duration, // DKG operation timeout pub malicious_threshold: u32, // Malicious participant threshold } * πŸ“ **Multi-signature Validation** * ROAST protocol for distributed signing * Threshold signature scheme (t-of-n) * Malicious signer detection and removal * Binding factor verification for signature shares * Dynamic participant management ### [3\. Network Security](https://book.arch.network/docs/setup-infrastructure/architecture#3-network-security) * 🌐 **Peer Validation** * Authenticated peer discovery * Message integrity verification * Rate limiting and DoS protection * Network topology validation * πŸ”„ **State Synchronization** * Consensus-driven state updates * Rollback capability for invalid states * Cross-validator state verification * Real-time conflict resolution [Performance Characteristics](https://book.arch.network/docs/setup-infrastructure/architecture#performance-characteristics) ---------------------------------------------------------------------------------------------------------------------------- ### [Scalability](https://book.arch.network/docs/setup-infrastructure/architecture#scalability) * πŸ“ˆ **Horizontal Scaling**: Add more validators for increased throughput * πŸ”„ **Parallel Processing**: Multiple transactions processed simultaneously * πŸ’Ύ **Efficient Storage**: Optimized data structures for fast access * 🌐 **Network Optimization**: Efficient peer-to-peer communication ### [Throughput](https://book.arch.network/docs/setup-infrastructure/architecture#throughput) * ⚑ **High TPS**: Optimized for high transaction throughput * πŸ’° **Low Latency**: Fast transaction confirmation * πŸ”„ **Batch Processing**: Efficient handling of multiple operations * πŸ“Š **Resource Management**: Compute budget optimization ### [Reliability](https://book.arch.network/docs/setup-infrastructure/architecture#reliability) * πŸ›‘οΈ **Fault Tolerance**: Continues operation despite node failures * πŸ”„ **Recovery**: Automatic recovery from network partitions * πŸ“ **Audit Trail**: Complete transaction history and state changes * πŸ” **Monitoring**: Real-time performance and health monitoring [Development Workflow](https://book.arch.network/docs/setup-infrastructure/architecture#development-workflow) -------------------------------------------------------------------------------------------------------------- ### [Local Development](https://book.arch.network/docs/setup-infrastructure/architecture#local-development) # Start complete local environment arch-cli orchestrate start --local "$(pwd)" # Use configuration profiles for different environments arch-cli config create-profile dev --bitcoin-node-endpoint http://127.0.0.1:18443 # Deploy and test programs arch-cli deploy target/deploy/ ### [Testing and Validation](https://book.arch.network/docs/setup-infrastructure/architecture#testing-and-validation) * πŸ§ͺ **Unit Testing**: Individual component testing * πŸ”„ **Integration Testing**: End-to-end workflow validation * 🌐 **Network Testing**: Multi-node network simulation * πŸ“Š **Performance Testing**: Throughput and latency measurement ### [Deployment](https://book.arch.network/docs/setup-infrastructure/architecture#deployment) * πŸš€ **Staged Rollouts**: Gradual feature deployment * πŸ”„ **Rollback Capability**: Quick reversion to previous versions * πŸ“Š **Monitoring**: Real-time performance and error tracking * πŸ” **Debugging**: Comprehensive logging and error reporting [Getting Started with the TypeScript SDK\ \ Previous Page](https://book.arch.network/docs/sdk/typescript/getting-started) [πŸ—οΈ Validator Setup\ \ Complete guide to setting up a full Arch Network validator node with Bitcoin Core and Titan indexer](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) ### On this page [Core Components](https://book.arch.network/docs/setup-infrastructure/architecture#core-components) [Arch VM](https://book.arch.network/docs/setup-infrastructure/architecture#arch-vm) [Bitcoin Integration](https://book.arch.network/docs/setup-infrastructure/architecture#bitcoin-integration) [Distributed Key Generation (DKG)](https://book.arch.network/docs/setup-infrastructure/architecture#distributed-key-generation-dkg) [Validator Network](https://book.arch.network/docs/setup-infrastructure/architecture#validator-network) [Node Types](https://book.arch.network/docs/setup-infrastructure/architecture#node-types) [Core Programs](https://book.arch.network/docs/setup-infrastructure/architecture#core-programs) [APL Token Program](https://book.arch.network/docs/setup-infrastructure/architecture#apl-token-program) [Associated Token Account (ATA)](https://book.arch.network/docs/setup-infrastructure/architecture#associated-token-account-ata) [Compute Budget Program](https://book.arch.network/docs/setup-infrastructure/architecture#compute-budget-program) [System Program](https://book.arch.network/docs/setup-infrastructure/architecture#system-program) [Transaction Flow](https://book.arch.network/docs/setup-infrastructure/architecture#transaction-flow) [Security Model](https://book.arch.network/docs/setup-infrastructure/architecture#security-model) [1\. UTXO Security](https://book.arch.network/docs/setup-infrastructure/architecture#1-utxo-security) [2\. Transaction Security](https://book.arch.network/docs/setup-infrastructure/architecture#2-transaction-security) [3\. Network Security](https://book.arch.network/docs/setup-infrastructure/architecture#3-network-security) [Performance Characteristics](https://book.arch.network/docs/setup-infrastructure/architecture#performance-characteristics) [Scalability](https://book.arch.network/docs/setup-infrastructure/architecture#scalability) [Throughput](https://book.arch.network/docs/setup-infrastructure/architecture#throughput) [Reliability](https://book.arch.network/docs/setup-infrastructure/architecture#reliability) [Development Workflow](https://book.arch.network/docs/setup-infrastructure/architecture#development-workflow) [Local Development](https://book.arch.network/docs/setup-infrastructure/architecture#local-development) [Testing and Validation](https://book.arch.network/docs/setup-infrastructure/architecture#testing-and-validation) [Deployment](https://book.arch.network/docs/setup-infrastructure/architecture#deployment) --- # SDK Reference APIs and Tools SDK Reference ============= Complete guide to Arch Network SDKs for building applications and programs The Arch Network ecosystem provides two distinct SDKs for building applications. Each SDK serves different use cases and development environments. This page will help you choose the right SDK for your project. [Available SDKs](https://book.arch.network/docs/tools-apis/sdk#available-sdks) ------------------------------------------------------------------------------- ### [1\. TypeScript SDK (by Saturn)](https://book.arch.network/docs/tools-apis/sdk#1-typescript-sdk-by-saturn) The **TypeScript SDK** is developed and maintained by Saturn (@saturnbtc) and provides a comprehensive JavaScript/TypeScript interface for interacting with the Arch Network. **Package**: `@saturnbtcio/arch-sdk` **Repository**: [arch-typescript-sdk](https://github.com/saturnbtc/arch-typescript-sdk) **Language**: TypeScript/JavaScript **Best for**: * Frontend applications (React, Vue, Angular) * Node.js backend services * Web3 applications * Rapid prototyping * JavaScript/TypeScript developers ### [2\. Rust SDK](https://book.arch.network/docs/tools-apis/sdk#2-rust-sdk) The **Rust SDK** is the native SDK included in the main Arch Network repository. It provides low-level access to all network features and is used for building high-performance applications and programs. **Package**: `arch_sdk` **Repository**: Part of [arch-network](https://github.com/Arch-Network/arch-network) **Language**: Rust **Best for**: * On-chain programs (smart contracts) * High-performance applications * System-level integrations * Validator/node development * Rust developers [Choosing the Right SDK](https://book.arch.network/docs/tools-apis/sdk#choosing-the-right-sdk) ----------------------------------------------------------------------------------------------- ### [Use the TypeScript SDK when:](https://book.arch.network/docs/tools-apis/sdk#use-the-typescript-sdk-when) * Building web applications or dApps * Working with Node.js backends * Integrating Arch Network into existing JavaScript projects * You need quick development cycles * Your team is more familiar with JavaScript/TypeScript ### [Use the Rust SDK when:](https://book.arch.network/docs/tools-apis/sdk#use-the-rust-sdk-when) * Writing on-chain programs for Arch Network * Building high-performance applications * Developing system-level tools or validators * You need maximum control and efficiency * Your team is comfortable with Rust [Quick Start Comparison](https://book.arch.network/docs/tools-apis/sdk#quick-start-comparison) ----------------------------------------------------------------------------------------------- ### [TypeScript SDK Installation](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-installation) npm install @saturnbtcio/arch-sdk # or yarn add @saturnbtcio/arch-sdk ### [Rust SDK Installation](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-installation) # In your Cargo.toml [dependencies] arch_sdk = "0.5.4" ### [Basic Connection Example](https://book.arch.network/docs/tools-apis/sdk#basic-connection-example) **TypeScript SDK:** import { Connection, Keypair } from '@saturnbtcio/arch-sdk'; const connection = new Connection('http://localhost:9002'); const keypair = Keypair.generate(); const isReady = await connection.isNodeReady(); console.log('Node ready:', isReady); **Rust SDK:** use arch_sdk::{Connection, Keypair}; #[tokio::main] async fn main() -> Result<(), Box> { let connection = Connection::new("http://localhost:9002"); let keypair = Keypair::new(); let is_ready = connection.is_node_ready().await?; println!("Node ready: {}", is_ready); Ok(()) } [Documentation Structure](https://book.arch.network/docs/tools-apis/sdk#documentation-structure) ------------------------------------------------------------------------------------------------- ### [TypeScript SDK Documentation](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-documentation) * [Getting Started with TypeScript SDK](https://book.arch.network/docs/tools-apis/sdk) * [TypeScript API Reference](https://book.arch.network/docs/tools-apis/sdk) * [TypeScript Examples](https://book.arch.network/docs/tools-apis/sdk) * [Web3 Integration](https://book.arch.network/docs/tools-apis/sdk) ### [Rust SDK Documentation](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-documentation) * [Getting Started with Rust SDK](https://book.arch.network/docs/tools-apis/sdk) * [Rust API Reference](https://book.arch.network/docs/tools-apis/sdk) * [Rust Examples](https://book.arch.network/docs/tools-apis/sdk) * [Program Development](https://book.arch.network/docs/tools-apis/sdk) [Feature Comparison](https://book.arch.network/docs/tools-apis/sdk#feature-comparison) --------------------------------------------------------------------------------------- | Feature | TypeScript SDK | Rust SDK | | --- | --- | --- | | **Connection Management** | βœ… | βœ… | | **Account Operations** | βœ… | βœ… | | **Transaction Building** | βœ… | βœ… | | **Program Deployment** | βœ… | βœ… | | **UTXO Management** | βœ… | βœ… | | **Bitcoin Integration** | βœ… | βœ… | | **Web3 Compatibility** | βœ… | ❌ | | **Browser Support** | βœ… | ❌ | | **Node.js Support** | βœ… | ❌ | | **On-chain Programs** | ❌ | βœ… | | **System Integration** | ❌ | βœ… | | **Performance** | Good | Excellent | | **Learning Curve** | Easy | Moderate | [Common Use Cases](https://book.arch.network/docs/tools-apis/sdk#common-use-cases) ----------------------------------------------------------------------------------- ### [Web Application Development](https://book.arch.network/docs/tools-apis/sdk#web-application-development) For building web applications, the TypeScript SDK is the clear choice: import { Connection, Keypair, Transaction } from '@saturnbtcio/arch-sdk'; // Connect to Arch Network const connection = new Connection('http://localhost:9002'); const keypair = Keypair.generate(); // Create and send a transaction const transaction = new Transaction(); transaction.addInstruction(/* your instruction */); const signature = await connection.sendTransaction(transaction, [keypair]); console.log('Transaction signature:', signature); ### [Smart Contract Development](https://book.arch.network/docs/tools-apis/sdk#smart-contract-development) For writing on-chain programs, use the Rust SDK: use arch_sdk::prelude::*; #[program] pub mod my_program { use super::*; pub fn initialize(ctx: Context) -> Result<()> { // Your program logic here Ok(()) } } #[derive(Accounts)] pub struct Initialize<'info> { // Your account definitions here } ### [Backend Services](https://book.arch.network/docs/tools-apis/sdk#backend-services) Both SDKs can be used for backend services, depending on your requirements: **TypeScript SDK (Node.js):** import { Connection } from '@saturnbtcio/arch-sdk'; const connection = new Connection('http://localhost:9002'); // Monitor transactions connection.onTransaction((tx) => { console.log('New transaction:', tx); }); **Rust SDK:** use arch_sdk::{Connection, Event}; #[tokio::main] async fn main() -> Result<(), Box> { let connection = Connection::new("http://localhost:9002"); // Monitor events let mut events = connection.subscribe_events().await?; while let Some(event) = events.next().await { println!("New event: {:?}", event); } Ok(()) } [Migration Guide](https://book.arch.network/docs/tools-apis/sdk#migration-guide) --------------------------------------------------------------------------------- ### [From Solana SDKs](https://book.arch.network/docs/tools-apis/sdk#from-solana-sdks) If you're coming from Solana development, both SDKs provide familiar patterns: **TypeScript (Solana β†’ Arch):** // Solana import { Connection } from '@solana/web3.js'; // Arch Network import { Connection } from '@saturnbtcio/arch-sdk'; **Rust (Solana β†’ Arch):** // Solana use solana_program::prelude::*; // Arch Network use arch_sdk::prelude::*; ### [From Bitcoin Libraries](https://book.arch.network/docs/tools-apis/sdk#from-bitcoin-libraries) For Bitcoin developers, the Rust SDK provides familiar UTXO patterns: use arch_sdk::{Utxo, Transaction, BitcoinAddress}; // Create a Bitcoin transaction let utxo = Utxo::new(/* utxo data */); let transaction = Transaction::new() .add_input(utxo) .add_output(/* output */); [Performance Considerations](https://book.arch.network/docs/tools-apis/sdk#performance-considerations) ------------------------------------------------------------------------------------------------------- ### [TypeScript SDK](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk) * **Pros**: Easy to use, great for rapid development * **Cons**: Higher overhead, not suitable for high-frequency operations * **Best for**: Web apps, prototypes, moderate transaction volumes ### [Rust SDK](https://book.arch.network/docs/tools-apis/sdk#rust-sdk) * **Pros**: High performance, low overhead, full feature access * **Cons**: Steeper learning curve, longer development time * **Best for**: High-performance apps, validators, system tools [Getting Help](https://book.arch.network/docs/tools-apis/sdk#getting-help) --------------------------------------------------------------------------- ### [TypeScript SDK Support](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-support) * **GitHub Issues**: [arch-typescript-sdk/issues](https://github.com/saturnbtc/arch-typescript-sdk/issues) * **Discord**: #typescript-sdk channel * **Documentation**: [TypeScript SDK Docs](https://book.arch.network/docs/tools-apis/sdk) ### [Rust SDK Support](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-support) * **GitHub Issues**: [arch-network/issues](https://github.com/Arch-Network/arch-network/issues) * **Discord**: #rust-sdk channel * **Documentation**: [Rust SDK Docs](https://book.arch.network/docs/tools-apis/sdk) [Next Steps](https://book.arch.network/docs/tools-apis/sdk#next-steps) ----------------------------------------------------------------------- [### TypeScript SDK\ \ Get started with the TypeScript SDK](https://book.arch.network/docs/tools-apis/sdk) [### Rust SDK\ \ Get started with the Rust SDK](https://book.arch.network/docs/tools-apis/sdk) [### Program Development\ \ Learn to write Arch programs](https://book.arch.network/docs/development/writing-your-first-program) [### Examples\ \ Explore SDK examples](https://book.arch.network/docs/tools-apis/sdk) [Resources](https://book.arch.network/docs/tools-apis/sdk#resources) --------------------------------------------------------------------- [### TypeScript SDK Repository\ \ Source code and issues](https://github.com/saturnbtc/arch-typescript-sdk) [### Arch Network Repository\ \ Rust SDK source code](https://github.com/Arch-Network/arch-network) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [### Arch Examples\ \ Example applications and programs](https://github.com/Arch-Network/arch-examples) [Arch CLI Reference Guide\ \ Complete reference for all Arch Network CLI commands and options](https://book.arch.network/docs/tools-apis/arch-cli-reference) ### On this page [Available SDKs](https://book.arch.network/docs/tools-apis/sdk#available-sdks) [1\. TypeScript SDK (by Saturn)](https://book.arch.network/docs/tools-apis/sdk#1-typescript-sdk-by-saturn) [2\. Rust SDK](https://book.arch.network/docs/tools-apis/sdk#2-rust-sdk) [Choosing the Right SDK](https://book.arch.network/docs/tools-apis/sdk#choosing-the-right-sdk) [Use the TypeScript SDK when:](https://book.arch.network/docs/tools-apis/sdk#use-the-typescript-sdk-when) [Use the Rust SDK when:](https://book.arch.network/docs/tools-apis/sdk#use-the-rust-sdk-when) [Quick Start Comparison](https://book.arch.network/docs/tools-apis/sdk#quick-start-comparison) [TypeScript SDK Installation](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-installation) [Rust SDK Installation](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-installation) [Basic Connection Example](https://book.arch.network/docs/tools-apis/sdk#basic-connection-example) [Documentation Structure](https://book.arch.network/docs/tools-apis/sdk#documentation-structure) [TypeScript SDK Documentation](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-documentation) [Rust SDK Documentation](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-documentation) [Feature Comparison](https://book.arch.network/docs/tools-apis/sdk#feature-comparison) [Common Use Cases](https://book.arch.network/docs/tools-apis/sdk#common-use-cases) [Web Application Development](https://book.arch.network/docs/tools-apis/sdk#web-application-development) [Smart Contract Development](https://book.arch.network/docs/tools-apis/sdk#smart-contract-development) [Backend Services](https://book.arch.network/docs/tools-apis/sdk#backend-services) [Migration Guide](https://book.arch.network/docs/tools-apis/sdk#migration-guide) [From Solana SDKs](https://book.arch.network/docs/tools-apis/sdk#from-solana-sdks) [From Bitcoin Libraries](https://book.arch.network/docs/tools-apis/sdk#from-bitcoin-libraries) [Performance Considerations](https://book.arch.network/docs/tools-apis/sdk#performance-considerations) [TypeScript SDK](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk) [Rust SDK](https://book.arch.network/docs/tools-apis/sdk#rust-sdk) [Getting Help](https://book.arch.network/docs/tools-apis/sdk#getting-help) [TypeScript SDK Support](https://book.arch.network/docs/tools-apis/sdk#typescript-sdk-support) [Rust SDK Support](https://book.arch.network/docs/tools-apis/sdk#rust-sdk-support) [Next Steps](https://book.arch.network/docs/tools-apis/sdk#next-steps) [Resources](https://book.arch.network/docs/tools-apis/sdk#resources) --- # Network Architecture Setup Infrastructure Network Architecture ==================== Understanding Arch Network's distributed system architecture and node interactions Arch Network operates as a distributed system with different types of nodes working together to provide secure and efficient program execution on Bitcoin. This document details the network's architecture and how different components interact. [Network Overview](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-overview) -------------------------------------------------------------------------------------------------------------- [Node Types](https://book.arch.network/docs/setup-infrastructure/network-architecture#node-types) -------------------------------------------------------------------------------------------------- ### [1\. Bootnode](https://book.arch.network/docs/setup-infrastructure/network-architecture#1-bootnode) The bootnode serves as the network's entry point, similar to DNS seeds in Bitcoin: * Handles initial network discovery * Maintains whitelist of valid validators * Coordinates peer connections * Manages network topology Configuration: cargo run -p bootnode -- \ --network-mode localnet \ --p2p-bind-port 19001 \ --leader-peer-id "" \ --validator-whitelist "" ### [2\. Leader Node](https://book.arch.network/docs/setup-infrastructure/network-architecture#2-leader-node) The leader node coordinates transaction processing and Bitcoin integration: Key responsibilities: * **Transaction Coordination**: Manages transaction flow and validation * **MultiSig Aggregation**: Collects and aggregates threshold signatures * **Bitcoin Integration**: Handles Bitcoin RPC communication * **Network Management**: Coordinates with validators and bootnode ### [3\. Validator Nodes](https://book.arch.network/docs/setup-infrastructure/network-architecture#3-validator-nodes) Validator nodes execute programs and participate in consensus: Validator responsibilities: * **Program Execution**: Run smart contracts in the Arch VM * **State Management**: Maintain program and account state * **Consensus Participation**: Contribute to threshold signatures * **Transaction Validation**: Verify transaction integrity [Network Communication](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-communication) ------------------------------------------------------------------------------------------------------------------------ ### [Message Flow](https://book.arch.network/docs/setup-infrastructure/network-architecture#message-flow) ### [Protocol Stack](https://book.arch.network/docs/setup-infrastructure/network-architecture#protocol-stack) [Security Model](https://book.arch.network/docs/setup-infrastructure/network-architecture#security-model) ---------------------------------------------------------------------------------------------------------- ### [Multi-Layer Security](https://book.arch.network/docs/setup-infrastructure/network-architecture#multi-layer-security) Arch Network implements security at multiple layers: 1. **Bitcoin Security**: Leverages Bitcoin's proven security guarantees 2. **Threshold Signatures**: No single validator can compromise the system 3. **Network Security**: Authenticated peer-to-peer communication 4. **Program Security**: Sandboxed execution environment ### [Threat Model](https://book.arch.network/docs/setup-infrastructure/network-architecture#threat-model) [Performance Characteristics](https://book.arch.network/docs/setup-infrastructure/network-architecture#performance-characteristics) ------------------------------------------------------------------------------------------------------------------------------------ ### [Scalability](https://book.arch.network/docs/setup-infrastructure/network-architecture#scalability) * **Horizontal Scaling**: Add more validators for increased throughput * **Parallel Processing**: Multiple transactions processed simultaneously * **Efficient State Management**: Optimized data structures for fast access * **Network Optimization**: Efficient peer-to-peer communication ### [Throughput](https://book.arch.network/docs/setup-infrastructure/network-architecture#throughput) * **High TPS**: Optimized for high transaction throughput * **Low Latency**: Fast transaction confirmation * **Batch Processing**: Efficient handling of multiple operations * **Resource Management**: Compute budget optimization ### [Reliability](https://book.arch.network/docs/setup-infrastructure/network-architecture#reliability) * **Fault Tolerance**: Continues operation despite node failures * **Recovery**: Automatic recovery from network partitions * **Audit Trail**: Complete transaction history and state changes * **Monitoring**: Real-time performance and health monitoring [Network Configuration](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-configuration) ------------------------------------------------------------------------------------------------------------------------ ### [Development Network](https://book.arch.network/docs/setup-infrastructure/network-architecture#development-network) # Start local development network arch-cli orchestrate start # Services: # - Bitcoin Core: http://127.0.0.1:18443 # - Titan API: http://127.0.0.1:8080 # - Validator RPC: http://127.0.0.1:9002 ### [Testnet Configuration](https://book.arch.network/docs/setup-infrastructure/network-architecture#testnet-configuration) # Configure for testnet arch-cli config create-profile testnet \ --bitcoin-node-endpoint http://bitcoin-rpc.test.arch.network:80 \ --bitcoin-network testnet \ --arch-node-url http://localhost:9002 ### [Production Network](https://book.arch.network/docs/setup-infrastructure/network-architecture#production-network) Production network configuration will be available when mainnet launches. [Monitoring and Telemetry](https://book.arch.network/docs/setup-infrastructure/network-architecture#monitoring-and-telemetry) ------------------------------------------------------------------------------------------------------------------------------ ### [Health Checks](https://book.arch.network/docs/setup-infrastructure/network-architecture#health-checks) # Check validator health curl http://localhost:9002/health # Check Bitcoin connection bitcoin-cli -regtest getblockchaininfo # Check Titan status curl http://localhost:8080/health ### [Metrics](https://book.arch.network/docs/setup-infrastructure/network-architecture#metrics) Key metrics to monitor: * **Transaction Throughput**: Transactions per second * **Block Production**: Block generation rate * **Network Latency**: Message propagation time * **Validator Participation**: Active validator count * **Bitcoin Sync**: Bitcoin blockchain synchronization status [Network Maintenance](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-maintenance) -------------------------------------------------------------------------------------------------------------------- ### [Validator Management](https://book.arch.network/docs/setup-infrastructure/network-architecture#validator-management) * **Adding Validators**: Update whitelist and restart network * **Removing Validators**: Graceful removal with state migration * **Validator Updates**: Rolling updates with minimal downtime * **Key Rotation**: Regular DKG sessions for security ### [Network Upgrades](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-upgrades) * **Protocol Upgrades**: Coordinated network-wide updates * **Feature Rollouts**: Gradual feature deployment * **Backward Compatibility**: Maintain compatibility with older versions * **Emergency Procedures**: Rapid response to critical issues [Next Steps](https://book.arch.network/docs/setup-infrastructure/network-architecture#next-steps) -------------------------------------------------------------------------------------------------- [### Bitcoin Integration\ \ Learn how Arch integrates with Bitcoin](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Consensus Mechanism\ \ Understand ROAST and FROST consensus](https://book.arch.network/docs/core-concepts/consensus) [### Validator Setup\ \ Set up your own validator node](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) [### Program Development\ \ Start building Arch programs](https://book.arch.network/docs/development/writing-your-first-program) [πŸ—οΈ Validator Setup\ \ Complete guide to setting up a full Arch Network validator node with Bitcoin Core and Titan indexer](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) [RPC API Reference\ \ Complete JSON-RPC API reference for interacting with Arch Network validator nodes](https://book.arch.network/docs/tools-apis/api-reference) ### On this page [Network Overview](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-overview) [Node Types](https://book.arch.network/docs/setup-infrastructure/network-architecture#node-types) [1\. Bootnode](https://book.arch.network/docs/setup-infrastructure/network-architecture#1-bootnode) [2\. Leader Node](https://book.arch.network/docs/setup-infrastructure/network-architecture#2-leader-node) [3\. Validator Nodes](https://book.arch.network/docs/setup-infrastructure/network-architecture#3-validator-nodes) [Network Communication](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-communication) [Message Flow](https://book.arch.network/docs/setup-infrastructure/network-architecture#message-flow) [Protocol Stack](https://book.arch.network/docs/setup-infrastructure/network-architecture#protocol-stack) [Security Model](https://book.arch.network/docs/setup-infrastructure/network-architecture#security-model) [Multi-Layer Security](https://book.arch.network/docs/setup-infrastructure/network-architecture#multi-layer-security) [Threat Model](https://book.arch.network/docs/setup-infrastructure/network-architecture#threat-model) [Performance Characteristics](https://book.arch.network/docs/setup-infrastructure/network-architecture#performance-characteristics) [Scalability](https://book.arch.network/docs/setup-infrastructure/network-architecture#scalability) [Throughput](https://book.arch.network/docs/setup-infrastructure/network-architecture#throughput) [Reliability](https://book.arch.network/docs/setup-infrastructure/network-architecture#reliability) [Network Configuration](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-configuration) [Development Network](https://book.arch.network/docs/setup-infrastructure/network-architecture#development-network) [Testnet Configuration](https://book.arch.network/docs/setup-infrastructure/network-architecture#testnet-configuration) [Production Network](https://book.arch.network/docs/setup-infrastructure/network-architecture#production-network) [Monitoring and Telemetry](https://book.arch.network/docs/setup-infrastructure/network-architecture#monitoring-and-telemetry) [Health Checks](https://book.arch.network/docs/setup-infrastructure/network-architecture#health-checks) [Metrics](https://book.arch.network/docs/setup-infrastructure/network-architecture#metrics) [Network Maintenance](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-maintenance) [Validator Management](https://book.arch.network/docs/setup-infrastructure/network-architecture#validator-management) [Network Upgrades](https://book.arch.network/docs/setup-infrastructure/network-architecture#network-upgrades) [Next Steps](https://book.arch.network/docs/setup-infrastructure/network-architecture#next-steps) --- # Arch CLI Reference Guide APIs and Tools Arch CLI Reference Guide ======================== Complete reference for all Arch Network CLI commands and options This comprehensive guide covers all available commands and options in the Arch Network CLI tool. [Table of Contents](https://book.arch.network/docs/tools-apis/arch-cli-reference#table-of-contents) ---------------------------------------------------------------------------------------------------- * [Global Options](https://book.arch.network/docs/tools-apis/arch-cli-reference#global-options) * [Configuration Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#configuration-management) * [Validator Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-management) * [Account Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#account-operations) * [Program Deployment](https://book.arch.network/docs/tools-apis/arch-cli-reference#program-deployment) * [Transaction Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#transaction-operations) * [Block and Network Info](https://book.arch.network/docs/tools-apis/arch-cli-reference#block-and-network-info) * [APL Token Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#apl-token-operations) * [Orchestration Commands](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-commands) * [Error Reference](https://book.arch.network/docs/tools-apis/arch-cli-reference#error-reference) [Global Options](https://book.arch.network/docs/tools-apis/arch-cli-reference#global-options) ---------------------------------------------------------------------------------------------- These options can be used with any command: # Specify network mode arch-cli --network-mode devnet|testnet|mainnet|localnet # Use configuration profile arch-cli --profile # Show help arch-cli --help # Show version arch-cli --version ::::note All user-facing identifiers in arch-cli (addresses, public keys, transaction IDs, block hashes) are base58. :::: **Network Modes:** * `devnet`: Development network (default) * `testnet`: Test network * `mainnet`: Production network * `localnet`: Local development network [Configuration Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#configuration-management) ------------------------------------------------------------------------------------------------------------------ ### [Create Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-profile) Create a new configuration profile for connecting to Bitcoin and Arch Network nodes: arch-cli config create-profile \ --bitcoin-node-endpoint \ --bitcoin-node-username \ --bitcoin-node-password \ --bitcoin-network \ --arch-node-url **Arguments:** * ``: Name of the profile * `--bitcoin-node-endpoint`: Bitcoin node endpoint URL (e.g., "[http://127.0.0.1:18443](http://127.0.0.1:18443/) ") * `--bitcoin-node-username`: Bitcoin node RPC username * `--bitcoin-node-password`: Bitcoin node RPC password * `--bitcoin-network`: Bitcoin network ("mainnet", "testnet", or "regtest") * `--arch-node-url`: Arch Network node URL **Example:** arch-cli config create-profile testnet \ --bitcoin-node-endpoint http://bitcoin-rpc.test.arch.network:80 \ --bitcoin-node-username bitcoin \ --bitcoin-node-password 0F_Ed53o4kR7nxh3xNaSQx-2M3TY16L55mz5y9fjdrk \ --bitcoin-network testnet \ --arch-node-url http://localhost:9002 ### [List Profiles](https://book.arch.network/docs/tools-apis/arch-cli-reference#list-profiles) List all available configuration profiles: arch-cli config list-profiles ### [Show Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-profile) Display detailed information about a specific profile: arch-cli config show-profile ### [Update Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#update-profile) Update an existing profile's settings: arch-cli config update-profile \ [--bitcoin-node-endpoint ] \ [--bitcoin-node-username ] \ [--bitcoin-node-password ] \ [--bitcoin-network ] \ [--arch-node-url ] ### [Set Default Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#set-default-profile) Set a profile as the default for all operations: arch-cli config set-default-profile [Validator Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-management) ---------------------------------------------------------------------------------------------------------- ### [Start Validator](https://book.arch.network/docs/tools-apis/arch-cli-reference#start-validator) Start a local validator node: arch-cli validator start \ [--bitcoin-node-endpoint ] \ [--bitcoin-node-username ] \ [--bitcoin-node-password ] \ [--bitcoin-network ] \ [--arch-node-url ] ### [Stop Validator](https://book.arch.network/docs/tools-apis/arch-cli-reference#stop-validator) Stop the running validator node: arch-cli validator stop ### [Validator Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-status) Check the status of the validator node: arch-cli validator status ### [Validator Logs](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-logs) View validator logs: arch-cli validator logs [--follow] [Account Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#account-operations) ------------------------------------------------------------------------------------------------------ ### [Create Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-account) Create a new account: arch-cli account create \ --keypair-path \ [--space ] \ [--owner ] **Arguments:** * `--keypair-path`: Path to the keypair file * `--space`: Account space in bytes (optional) * `--owner`: Program ID that owns the account (optional) ### [Airdrop](https://book.arch.network/docs/tools-apis/arch-cli-reference#airdrop) Request an airdrop of lamports to an account: arch-cli account airdrop \ --keypair-path \ [--amount ] **Arguments:** * `--keypair-path`: Path to the keypair file * `--amount`: Amount of lamports to airdrop (optional, defaults to 1 SOL) ### [Show Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-account) Display account information: arch-cli account show ### [Show Balance](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-balance) Display account balance: arch-cli account balance [Program Deployment](https://book.arch.network/docs/tools-apis/arch-cli-reference#program-deployment) ------------------------------------------------------------------------------------------------------ ### [Deploy Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#deploy-program) Deploy a program to the network: arch-cli program deploy \ [--program-id ] \ [--keypair-path ] **Arguments:** * ``: Path to the compiled program (.so file) * `--program-id`: Program ID keypair path (optional) * `--keypair-path`: Payer keypair path (optional) ### [Show Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-program) Display program information: arch-cli program show ### [Call Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#call-program) Call a program with specific instructions: arch-cli program call \ --accounts \ --instruction-data \ [--keypair-path ] **Arguments:** * ``: Program ID to call * `--accounts`: Comma-separated list of account keypair paths * `--instruction-data`: Base64-encoded instruction data * `--keypair-path`: Payer keypair path (optional) [Transaction Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#transaction-operations) -------------------------------------------------------------------------------------------------------------- ### [Send Transaction](https://book.arch.network/docs/tools-apis/arch-cli-reference#send-transaction) Send a transaction to the network: arch-cli transaction send \ [--keypair-path ] ### [Show Transaction](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-transaction) Display transaction information: arch-cli transaction show ### [Transaction Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#transaction-status) Check transaction status: arch-cli transaction status [Block and Network Info](https://book.arch.network/docs/tools-apis/arch-cli-reference#block-and-network-info) -------------------------------------------------------------------------------------------------------------- ### [Get Block Height](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block-height) Get the current block height: arch-cli get-block-height ### [Get Block Hash](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block-hash) Get the block hash for a specific height: arch-cli get-block-hash ### [Get Block](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block) Get block information: arch-cli get-block ### [Network Info](https://book.arch.network/docs/tools-apis/arch-cli-reference#network-info) Get network information: arch-cli network info [APL Token Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#apl-token-operations) ---------------------------------------------------------------------------------------------------------- ### [Create Token Mint](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-token-mint) Create a new token mint: arch-cli token create-mint \ --decimals \ --mint-authority \ [--mint-keypair-path ] \ [--keypair-path ] **Arguments:** * `--decimals`: Number of decimal places * `--mint-authority`: Path to mint authority keypair * `--mint-keypair-path`: Path to mint keypair (optional) * `--keypair-path`: Payer keypair path (optional) ### [Create Token Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-token-account) Create a new token account: arch-cli token create-account \ --mint \ --owner \ [--keypair-path ] **Arguments:** * `--mint`: Token mint address * `--owner`: Path to owner keypair * `--keypair-path`: Payer keypair path (optional) ### [Mint Tokens](https://book.arch.network/docs/tools-apis/arch-cli-reference#mint-tokens) Mint tokens to an account: arch-cli token mint-to \ --mint \ --destination \ --amount \ --mint-authority \ [--keypair-path ] **Arguments:** * `--mint`: Token mint address * `--destination`: Destination token account address * `--amount`: Amount of tokens to mint * `--mint-authority`: Path to mint authority keypair * `--keypair-path`: Payer keypair path (optional) ### [Transfer Tokens](https://book.arch.network/docs/tools-apis/arch-cli-reference#transfer-tokens) Transfer tokens between accounts: arch-cli token transfer \ --source \ --destination \ --amount \ --owner \ [--keypair-path ] **Arguments:** * `--source`: Source token account address * `--destination`: Destination token account address * `--amount`: Amount of tokens to transfer * `--owner`: Path to owner keypair * `--keypair-path`: Payer keypair path (optional) ### [Show Token Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-token-account) Display token account information: arch-cli token show-account \ --mint \ --owner ### [Show Token Mint](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-token-mint) Display token mint information: arch-cli token show-mint [Orchestration Commands](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-commands) -------------------------------------------------------------------------------------------------------------- ### [Start Orchestration](https://book.arch.network/docs/tools-apis/arch-cli-reference#start-orchestration) Start the complete local development environment: arch-cli orchestrate start \ [--bitcoin-node-endpoint ] \ [--bitcoin-node-username ] \ [--bitcoin-node-password ] \ [--bitcoin-network ] ### [Stop Orchestration](https://book.arch.network/docs/tools-apis/arch-cli-reference#stop-orchestration) Stop the local development environment: arch-cli orchestrate stop ### [Orchestration Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-status) Check the status of orchestrated services: arch-cli orchestrate status ### [Orchestration Logs](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-logs) View logs from orchestrated services: arch-cli orchestrate logs [--service ] [Error Reference](https://book.arch.network/docs/tools-apis/arch-cli-reference#error-reference) ------------------------------------------------------------------------------------------------ ### [Common Error Codes](https://book.arch.network/docs/tools-apis/arch-cli-reference#common-error-codes) | Code | Description | Solution | | --- | --- | --- | | `InvalidKeypair` | Invalid keypair format | Check keypair file path and format | | `InsufficientFunds` | Not enough lamports | Request an airdrop or add funds | | `AccountNotFound` | Account doesn't exist | Create the account first | | `ProgramNotFound` | Program doesn't exist | Deploy the program first | | `InvalidInstruction` | Invalid instruction data | Check instruction format and data | | `NetworkError` | Network connection failed | Check network connectivity and endpoints | ### [Troubleshooting](https://book.arch.network/docs/tools-apis/arch-cli-reference#troubleshooting) **Connection Issues:** # Check if the node is running arch-cli validator status # Check network connectivity curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "is_node_ready", "params": []}' **Account Issues:** # Check account balance arch-cli account balance # Check account info arch-cli account show **Program Issues:** # Check program info arch-cli program show # Check program accounts arch-cli program accounts [Best Practices](https://book.arch.network/docs/tools-apis/arch-cli-reference#best-practices) ---------------------------------------------------------------------------------------------- ### [1\. Configuration Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#1-configuration-management) * Use profiles for different environments * Keep sensitive information secure * Use environment variables for passwords ### [2\. Keypair Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#2-keypair-management) * Store keypairs securely * Use different keypairs for different purposes * Backup important keypairs ### [3\. Transaction Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#3-transaction-management) * Always check transaction status * Use appropriate fees * Handle errors gracefully ### [4\. Development Workflow](https://book.arch.network/docs/tools-apis/arch-cli-reference#4-development-workflow) * Use local development environment * Test thoroughly before deploying * Monitor logs for issues [Examples](https://book.arch.network/docs/tools-apis/arch-cli-reference#examples) ---------------------------------------------------------------------------------- ### [Complete Development Setup](https://book.arch.network/docs/tools-apis/arch-cli-reference#complete-development-setup) # 1. Start local environment arch-cli orchestrate start # 2. Create a profile arch-cli config create-profile local \ --bitcoin-node-endpoint http://127.0.0.1:18443 \ --bitcoin-node-username bitcoin \ --bitcoin-node-password bitcoinpass \ --bitcoin-network regtest \ --arch-node-url http://localhost:9002 # 3. Set as default arch-cli config set-default-profile local # 4. Create and fund an account arch-cli account create --keypair-path ~/my_account.key arch-cli account airdrop --keypair-path ~/my_account.key # 5. Deploy a program arch-cli program deploy target/deploy/my_program.so \ --keypair-path ~/my_account.key # 6. Check status arch-cli validator status arch-cli get-block-height ### [Token Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#token-operations) # 1. Create a token mint arch-cli token create-mint \ --decimals 9 \ --mint-authority ~/mint_authority.key \ --keypair-path ~/payer.key # 2. Create a token account arch-cli token create-account \ --mint \ --owner ~/owner.key \ --keypair-path ~/payer.key # 3. Mint tokens arch-cli token mint-to \ --mint \ --destination \ --amount 1000000000 \ --mint-authority ~/mint_authority.key \ --keypair-path ~/payer.key # 4. Transfer tokens arch-cli token transfer \ --source \ --destination \ --amount 500000000 \ --owner ~/owner.key \ --keypair-path ~/payer.key [Next Steps](https://book.arch.network/docs/tools-apis/arch-cli-reference#next-steps) -------------------------------------------------------------------------------------- [### Quick Start Guide\ \ Get started with Arch Network development](https://book.arch.network/docs/quick-start/quick-start) [### Program Development\ \ Learn to write Arch programs](https://book.arch.network/docs/development/writing-your-first-program) [### Token Creation\ \ Create your first token](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### RPC API Reference\ \ Use the RPC API directly](https://book.arch.network/docs/tools-apis/api-reference) [Resources](https://book.arch.network/docs/tools-apis/arch-cli-reference#resources) ------------------------------------------------------------------------------------ [### Arch Network Repository\ \ Source code and issues](https://github.com/Arch-Network/arch-network) [### Arch Examples\ \ Example programs and applications](https://github.com/Arch-Network/arch-examples) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [### Arch Network Website\ \ Official website and announcements](https://arch.network/) [RPC API Reference\ \ Complete JSON-RPC API reference for interacting with Arch Network validator nodes](https://book.arch.network/docs/tools-apis/api-reference) [SDK Reference\ \ Complete guide to Arch Network SDKs for building applications and programs](https://book.arch.network/docs/tools-apis/sdk) ### On this page [Table of Contents](https://book.arch.network/docs/tools-apis/arch-cli-reference#table-of-contents) [Global Options](https://book.arch.network/docs/tools-apis/arch-cli-reference#global-options) [Configuration Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#configuration-management) [Create Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-profile) [List Profiles](https://book.arch.network/docs/tools-apis/arch-cli-reference#list-profiles) [Show Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-profile) [Update Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#update-profile) [Set Default Profile](https://book.arch.network/docs/tools-apis/arch-cli-reference#set-default-profile) [Validator Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-management) [Start Validator](https://book.arch.network/docs/tools-apis/arch-cli-reference#start-validator) [Stop Validator](https://book.arch.network/docs/tools-apis/arch-cli-reference#stop-validator) [Validator Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-status) [Validator Logs](https://book.arch.network/docs/tools-apis/arch-cli-reference#validator-logs) [Account Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#account-operations) [Create Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-account) [Airdrop](https://book.arch.network/docs/tools-apis/arch-cli-reference#airdrop) [Show Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-account) [Show Balance](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-balance) [Program Deployment](https://book.arch.network/docs/tools-apis/arch-cli-reference#program-deployment) [Deploy Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#deploy-program) [Show Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-program) [Call Program](https://book.arch.network/docs/tools-apis/arch-cli-reference#call-program) [Transaction Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#transaction-operations) [Send Transaction](https://book.arch.network/docs/tools-apis/arch-cli-reference#send-transaction) [Show Transaction](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-transaction) [Transaction Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#transaction-status) [Block and Network Info](https://book.arch.network/docs/tools-apis/arch-cli-reference#block-and-network-info) [Get Block Height](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block-height) [Get Block Hash](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block-hash) [Get Block](https://book.arch.network/docs/tools-apis/arch-cli-reference#get-block) [Network Info](https://book.arch.network/docs/tools-apis/arch-cli-reference#network-info) [APL Token Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#apl-token-operations) [Create Token Mint](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-token-mint) [Create Token Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#create-token-account) [Mint Tokens](https://book.arch.network/docs/tools-apis/arch-cli-reference#mint-tokens) [Transfer Tokens](https://book.arch.network/docs/tools-apis/arch-cli-reference#transfer-tokens) [Show Token Account](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-token-account) [Show Token Mint](https://book.arch.network/docs/tools-apis/arch-cli-reference#show-token-mint) [Orchestration Commands](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-commands) [Start Orchestration](https://book.arch.network/docs/tools-apis/arch-cli-reference#start-orchestration) [Stop Orchestration](https://book.arch.network/docs/tools-apis/arch-cli-reference#stop-orchestration) [Orchestration Status](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-status) [Orchestration Logs](https://book.arch.network/docs/tools-apis/arch-cli-reference#orchestration-logs) [Error Reference](https://book.arch.network/docs/tools-apis/arch-cli-reference#error-reference) [Common Error Codes](https://book.arch.network/docs/tools-apis/arch-cli-reference#common-error-codes) [Troubleshooting](https://book.arch.network/docs/tools-apis/arch-cli-reference#troubleshooting) [Best Practices](https://book.arch.network/docs/tools-apis/arch-cli-reference#best-practices) [1\. Configuration Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#1-configuration-management) [2\. Keypair Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#2-keypair-management) [3\. Transaction Management](https://book.arch.network/docs/tools-apis/arch-cli-reference#3-transaction-management) [4\. Development Workflow](https://book.arch.network/docs/tools-apis/arch-cli-reference#4-development-workflow) [Examples](https://book.arch.network/docs/tools-apis/arch-cli-reference#examples) [Complete Development Setup](https://book.arch.network/docs/tools-apis/arch-cli-reference#complete-development-setup) [Token Operations](https://book.arch.network/docs/tools-apis/arch-cli-reference#token-operations) [Next Steps](https://book.arch.network/docs/tools-apis/arch-cli-reference#next-steps) [Resources](https://book.arch.network/docs/tools-apis/arch-cli-reference#resources) --- # Associated Token Account Program APL (Arch Program Library) Associated Token Account Program ================================ Complete guide to the APL Associated Token Account Program for deterministic token account management The Associated Token Account (ATA) Program is a utility program in the APL that standardizes the creation and management of token accounts. It provides a deterministic way to find and create token accounts for any wallet address and token mint combination. [Overview](https://book.arch.network/docs/apl/associated-token-account#overview) --------------------------------------------------------------------------------- The Associated Token Account Program enables: * **Deterministic derivation of token account addresses** * **Automatic token account creation** * **Standardized account management** * **Simplified token operations** [Program ID](https://book.arch.network/docs/apl/associated-token-account#program-id) ------------------------------------------------------------------------------------- AssociatedTokenAccount1111111111 You can get the program ID in code: let program_id = apl_associated_token_account::id(); [Core Concepts](https://book.arch.network/docs/apl/associated-token-account#core-concepts) ------------------------------------------------------------------------------------------- ### [Associated Token Accounts](https://book.arch.network/docs/apl/associated-token-account#associated-token-accounts) An Associated Token Account is a Program Derived Address (PDA) that is deterministically derived from: * The wallet owner's public key * The token mint address This ensures that: 1. **Each wallet can have exactly one associated token account per token mint** 2. **The account address can be derived by anyone who knows the wallet and mint addresses** 3. **The account ownership and permissions are standardized** ### [Account Structure](https://book.arch.network/docs/apl/associated-token-account#account-structure) The Associated Token Account follows the standard Token Account structure but with additional guarantees about its address derivation and ownership. ### [How It Works](https://book.arch.network/docs/apl/associated-token-account#how-it-works) 1. **Address Derivation**: Given a wallet and token mint, the ATA address is derived deterministically 2. **Account Creation**: If the account doesn't exist, it can be created by calling the ATA program 3. **Token Operations**: Once created, the ATA works like any other token account for transfers, approvals, etc. The key advantage is that applications can always find a user's token account for any mint without needing to store addresses. ### [Key Functions](https://book.arch.network/docs/apl/associated-token-account#key-functions) The main function for working with Associated Token Accounts: // Derive address and bump seed let (address, bump_seed) = apl_associated_token_account::get_associated_token_address_and_bump_seed( &wallet_pubkey, &token_mint_pubkey, &apl_associated_token_account::id(), ); [Instructions](https://book.arch.network/docs/apl/associated-token-account#instructions) ----------------------------------------------------------------------------------------- ### [Create Associated Token Account](https://book.arch.network/docs/apl/associated-token-account#create-associated-token-account) Creates a new associated token account for a wallet and token mint combination. **Required accounts:** * `[signer]` Funding account (pays for account creation) * `[writable]` New associated token account * `[]` Wallet address (account owner) * `[]` Token mint * `[]` System program * `[]` Token program **Example:** // Derive the associated token account address let (associated_token_address, _bump_seed) = apl_associated_token_account::get_associated_token_address_and_bump_seed( &wallet_address, &token_mint, &apl_associated_token_account::id(), ); // Create instruction to create the associated token account let instruction = arch_program::instruction::Instruction { program_id: apl_associated_token_account::id(), accounts: vec![\ arch_program::account::AccountMeta::new(payer_pubkey, true),\ arch_program::account::AccountMeta::new(associated_token_address, false),\ arch_program::account::AccountMeta::new(wallet_address, false),\ arch_program::account::AccountMeta::new_readonly(token_mint, false),\ arch_program::account::AccountMeta::new_readonly(arch_program::system_program::id(), false),\ arch_program::account::AccountMeta::new_readonly(apl_token::id(), false),\ ], data: utxo_data, // UTXO data for account creation }; [Best Practices](https://book.arch.network/docs/apl/associated-token-account#best-practices) --------------------------------------------------------------------------------------------- ### [Account Management](https://book.arch.network/docs/apl/associated-token-account#account-management) 1. **Creation** * Always check if the account exists before creating * Use the deterministic derivation function * Handle creation errors gracefully 2. **Address Derivation** * Use the official derivation function * Store the bump seed for future reference * Validate derived addresses 3. **Error Handling** * Check for account existence * Handle insufficient funds for creation * Validate account ownership ### [Security Considerations](https://book.arch.network/docs/apl/associated-token-account#security-considerations) 1. **Address Validation** * Always verify derived addresses * Check account ownership before operations * Validate mint addresses 2. **Access Control** * Ensure proper authority for account creation * Validate wallet ownership * Check token program compatibility [Usage Examples](https://book.arch.network/docs/apl/associated-token-account#usage-examples) --------------------------------------------------------------------------------------------- ### [Basic ATA Creation](https://book.arch.network/docs/apl/associated-token-account#basic-ata-creation) use arch_sdk::prelude::*; use apl_associated_token_account::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to Arch Network let client = ArchNetworkClient::new("http://localhost:9002").await?; // Create keypairs let wallet = Keypair::new(); let payer = Keypair::new(); let token_mint = Pubkey::new_unique(); // Derive the associated token account address let (ata_address, bump_seed) = get_associated_token_address_and_bump_seed( &wallet.pubkey(), &token_mint, &apl_associated_token_account::id(), ); // Create the associated token account let instruction = create_associated_token_account( &payer.pubkey(), &wallet.pubkey(), &token_mint, &apl_token::id(), ); // Send transaction let transaction = Transaction::new() .add_instruction(instruction); let signature = client.send_transaction(transaction, &[&payer]).await?; println!("ATA created: {}", signature); Ok(()) } ### [Check ATA Existence](https://book.arch.network/docs/apl/associated-token-account#check-ata-existence) async fn check_ata_exists( client: &ArchNetworkClient, wallet: &Pubkey, mint: &Pubkey, ) -> Result> { // Derive the ATA address let (ata_address, _) = get_associated_token_address_and_bump_seed( wallet, mint, &apl_associated_token_account::id(), ); // Check if account exists match client.get_account_info(&ata_address).await { Ok(Some(_)) => Ok(true), Ok(None) => Ok(false), Err(_) => Ok(false), } } ### [Create ATA if Not Exists](https://book.arch.network/docs/apl/associated-token-account#create-ata-if-not-exists) async fn create_ata_if_not_exists( client: &ArchNetworkClient, wallet: &Pubkey, mint: &Pubkey, payer: &Keypair, ) -> Result> { // Derive the ATA address let (ata_address, _) = get_associated_token_address_and_bump_seed( wallet, mint, &apl_associated_token_account::id(), ); // Check if account exists if !check_ata_exists(client, wallet, mint).await? { // Create the ATA let instruction = create_associated_token_account( &payer.pubkey(), wallet, mint, &apl_token::id(), ); let transaction = Transaction::new() .add_instruction(instruction); client.send_transaction(transaction, &[payer]).await?; } Ok(ata_address) } [CLI Usage](https://book.arch.network/docs/apl/associated-token-account#cli-usage) ----------------------------------------------------------------------------------- ### [Create Associated Token Account](https://book.arch.network/docs/apl/associated-token-account#create-associated-token-account-1) # Create an associated token account arch-cli token create-associated-account \ --wallet \ --mint \ --keypair-path ~/payer.key ### [Get Associated Token Account Address](https://book.arch.network/docs/apl/associated-token-account#get-associated-token-account-address) # Get the associated token account address arch-cli token get-associated-account-address \ --wallet \ --mint [Integration with Token Program](https://book.arch.network/docs/apl/associated-token-account#integration-with-token-program) ----------------------------------------------------------------------------------------------------------------------------- ### [Transfer to ATA](https://book.arch.network/docs/apl/associated-token-account#transfer-to-ata) async fn transfer_to_ata( client: &ArchNetworkClient, source: &Pubkey, destination_wallet: &Pubkey, mint: &Pubkey, amount: u64, owner: &Keypair, payer: &Keypair, ) -> Result<(), Box> { // Ensure destination ATA exists let destination_ata = create_ata_if_not_exists( client, destination_wallet, mint, payer, ).await?; // Transfer tokens let transfer_instruction = apl_token::instruction::transfer( &apl_token::id(), source, &destination_ata, &owner.pubkey(), &[], amount, )?; let transaction = Transaction::new() .add_instruction(transfer_instruction); client.send_transaction(transaction, &[owner, payer]).await?; Ok(()) } ### [Mint to ATA](https://book.arch.network/docs/apl/associated-token-account#mint-to-ata) async fn mint_to_ata( client: &ArchNetworkClient, mint: &Pubkey, destination_wallet: &Pubkey, amount: u64, mint_authority: &Keypair, payer: &Keypair, ) -> Result<(), Box> { // Ensure destination ATA exists let destination_ata = create_ata_if_not_exists( client, destination_wallet, mint, payer, ).await?; // Mint tokens let mint_instruction = apl_token::instruction::mint_to( &apl_token::id(), mint, &destination_ata, &mint_authority.pubkey(), &[], amount, )?; let transaction = Transaction::new() .add_instruction(mint_instruction); client.send_transaction(transaction, &[mint_authority, payer]).await?; Ok(()) } [Advanced Patterns](https://book.arch.network/docs/apl/associated-token-account#advanced-patterns) --------------------------------------------------------------------------------------------------- ### [Batch ATA Creation](https://book.arch.network/docs/apl/associated-token-account#batch-ata-creation) async fn create_multiple_atas( client: &ArchNetworkClient, wallet: &Pubkey, mints: &[Pubkey], payer: &Keypair, ) -> Result, Box> { let mut instructions = Vec::new(); let mut ata_addresses = Vec::new(); for mint in mints { let (ata_address, _) = get_associated_token_address_and_bump_seed( wallet, mint, &apl_associated_token_account::id(), ); // Check if ATA exists if !check_ata_exists(client, wallet, mint).await? { let instruction = create_associated_token_account( &payer.pubkey(), wallet, mint, &apl_token::id(), ); instructions.push(instruction); } ata_addresses.push(ata_address); } // Send batch transaction if !instructions.is_empty() { let transaction = Transaction::new() .add_instructions(instructions); client.send_transaction(transaction, &[payer]).await?; } Ok(ata_addresses) } ### [ATA with Custom Program](https://book.arch.network/docs/apl/associated-token-account#ata-with-custom-program) async fn create_ata_with_custom_program( client: &ArchNetworkClient, wallet: &Pubkey, mint: &Pubkey, custom_program: &Pubkey, payer: &Keypair, ) -> Result> { // Derive ATA address for custom program let (ata_address, _) = get_associated_token_address_and_bump_seed( wallet, mint, custom_program, ); // Create instruction with custom program let instruction = create_associated_token_account( &payer.pubkey(), wallet, mint, custom_program, ); let transaction = Transaction::new() .add_instruction(instruction); client.send_transaction(transaction, &[payer]).await?; Ok(ata_address) } [Error Handling](https://book.arch.network/docs/apl/associated-token-account#error-handling) --------------------------------------------------------------------------------------------- ### [Common Errors](https://book.arch.network/docs/apl/associated-token-account#common-errors) | Error | Description | Solution | | --- | --- | --- | | `AccountAlreadyExists` | ATA already exists | Check existence before creation | | `InvalidMint` | Invalid token mint | Validate mint address | | `InvalidOwner` | Invalid wallet owner | Check wallet address | | `InsufficientFunds` | Not enough for account creation | Fund the payer account | ### [Error Handling Example](https://book.arch.network/docs/apl/associated-token-account#error-handling-example) async fn safe_create_ata( client: &ArchNetworkClient, wallet: &Pubkey, mint: &Pubkey, payer: &Keypair, ) -> Result, Box> { // Derive ATA address let (ata_address, _) = get_associated_token_address_and_bump_seed( wallet, mint, &apl_associated_token_account::id(), ); // Check if already exists if check_ata_exists(client, wallet, mint).await? { return Ok(Some(ata_address)); } // Try to create match create_ata_if_not_exists(client, wallet, mint, payer).await { Ok(address) => Ok(Some(address)), Err(e) => { eprintln!("Failed to create ATA: {}", e); Ok(None) } } } [Best Practices](https://book.arch.network/docs/apl/associated-token-account#best-practices-1) ----------------------------------------------------------------------------------------------- ### [1\. Address Management](https://book.arch.network/docs/apl/associated-token-account#1-address-management) * Always use the official derivation function * Store derived addresses for future reference * Validate addresses before use ### [2\. Account Creation](https://book.arch.network/docs/apl/associated-token-account#2-account-creation) * Check existence before creating * Handle creation errors gracefully * Use batch operations when possible ### [3\. Integration](https://book.arch.network/docs/apl/associated-token-account#3-integration) * Integrate with token operations seamlessly * Use ATA for all user-facing token operations * Implement proper error handling ### [4\. Performance](https://book.arch.network/docs/apl/associated-token-account#4-performance) * Batch ATA creation when possible * Cache derived addresses * Minimize account creation calls [Next Steps](https://book.arch.network/docs/apl/associated-token-account#next-steps) ------------------------------------------------------------------------------------- [### Token Program\ \ Learn about the APL Token Program](https://book.arch.network/docs/APL/token-program) [### Token Creation Guide\ \ Create your first token with ATA](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### SDK Reference\ \ Use SDKs for easier integration](https://book.arch.network/docs/tools-apis/sdk) [### CLI Reference\ \ Use CLI for ATA operations](https://book.arch.network/docs/tools-apis/arch-cli-reference) [Resources](https://book.arch.network/docs/apl/associated-token-account#resources) ----------------------------------------------------------------------------------- [### Token Program\ \ Complete APL Token Program reference](https://book.arch.network/docs/APL/token-program) [### Arch Examples\ \ Example implementations](https://github.com/Arch-Network/arch-examples) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [Welcome to Arch Network\ \ A Bitcoin-native computation environment that enhances Bitcoin's capabilities through specialized virtual machine operations](https://book.arch.network/docs) [Introduction to the Arch Program Library (APL)\ \ A collection of on-chain programs providing fundamental building blocks for Arch Network dApps](https://book.arch.network/docs/apl/introduction) ### On this page [Overview](https://book.arch.network/docs/apl/associated-token-account#overview) [Program ID](https://book.arch.network/docs/apl/associated-token-account#program-id) [Core Concepts](https://book.arch.network/docs/apl/associated-token-account#core-concepts) [Associated Token Accounts](https://book.arch.network/docs/apl/associated-token-account#associated-token-accounts) [Account Structure](https://book.arch.network/docs/apl/associated-token-account#account-structure) [How It Works](https://book.arch.network/docs/apl/associated-token-account#how-it-works) [Key Functions](https://book.arch.network/docs/apl/associated-token-account#key-functions) [Instructions](https://book.arch.network/docs/apl/associated-token-account#instructions) [Create Associated Token Account](https://book.arch.network/docs/apl/associated-token-account#create-associated-token-account) [Best Practices](https://book.arch.network/docs/apl/associated-token-account#best-practices) [Account Management](https://book.arch.network/docs/apl/associated-token-account#account-management) [Security Considerations](https://book.arch.network/docs/apl/associated-token-account#security-considerations) [Usage Examples](https://book.arch.network/docs/apl/associated-token-account#usage-examples) [Basic ATA Creation](https://book.arch.network/docs/apl/associated-token-account#basic-ata-creation) [Check ATA Existence](https://book.arch.network/docs/apl/associated-token-account#check-ata-existence) [Create ATA if Not Exists](https://book.arch.network/docs/apl/associated-token-account#create-ata-if-not-exists) [CLI Usage](https://book.arch.network/docs/apl/associated-token-account#cli-usage) [Create Associated Token Account](https://book.arch.network/docs/apl/associated-token-account#create-associated-token-account-1) [Get Associated Token Account Address](https://book.arch.network/docs/apl/associated-token-account#get-associated-token-account-address) [Integration with Token Program](https://book.arch.network/docs/apl/associated-token-account#integration-with-token-program) [Transfer to ATA](https://book.arch.network/docs/apl/associated-token-account#transfer-to-ata) [Mint to ATA](https://book.arch.network/docs/apl/associated-token-account#mint-to-ata) [Advanced Patterns](https://book.arch.network/docs/apl/associated-token-account#advanced-patterns) [Batch ATA Creation](https://book.arch.network/docs/apl/associated-token-account#batch-ata-creation) [ATA with Custom Program](https://book.arch.network/docs/apl/associated-token-account#ata-with-custom-program) [Error Handling](https://book.arch.network/docs/apl/associated-token-account#error-handling) [Common Errors](https://book.arch.network/docs/apl/associated-token-account#common-errors) [Error Handling Example](https://book.arch.network/docs/apl/associated-token-account#error-handling-example) [Best Practices](https://book.arch.network/docs/apl/associated-token-account#best-practices-1) [1\. Address Management](https://book.arch.network/docs/apl/associated-token-account#1-address-management) [2\. Account Creation](https://book.arch.network/docs/apl/associated-token-account#2-account-creation) [3\. Integration](https://book.arch.network/docs/apl/associated-token-account#3-integration) [4\. Performance](https://book.arch.network/docs/apl/associated-token-account#4-performance) [Next Steps](https://book.arch.network/docs/apl/associated-token-account#next-steps) [Resources](https://book.arch.network/docs/apl/associated-token-account#resources) --- # System Requirements Quick Start System Requirements =================== Hardware and software requirements for Arch Network development Welcome to the Arch Network development guide. This page contains all the requirements and setup instructions needed to start developing with Arch Network. [System Requirements](https://book.arch.network/docs/quick-start/requirements#system-requirements) --------------------------------------------------------------------------------------------------- ### [Hardware Requirements](https://book.arch.network/docs/quick-start/requirements#hardware-requirements) | Component | Minimum | Recommended | | --- | --- | --- | | CPU | 4+ cores | 8+ cores | | RAM | 16GB | 32GB | | Storage | 100GB SSD | 500GB+ SSD | | Network | 100Mbps | 1Gbps+ | ### [Software Requirements](https://book.arch.network/docs/quick-start/requirements#software-requirements) | Requirement | Minimum Version | Description | | --- | --- | --- | | Operating System | Ubuntu 20.04+ / macOS 12.0+ | Latest LTS recommended | | Git | Latest | Version control | | Rust | Latest stable | Core development language | | Solana CLI | v2.0+ | Program compilation tools | | Arch Network CLI | Latest | Development toolkit | [Installation Guide](https://book.arch.network/docs/quick-start/requirements#installation-guide) ------------------------------------------------------------------------------------------------- ### [1\. Install Rust](https://book.arch.network/docs/quick-start/requirements#1-install-rust) # Install Rust using rustup curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # Add Rust to your current shell session # Verify installation rustc --version cargo --version ### [2\. Install Build Tools](https://book.arch.network/docs/quick-start/requirements#2-install-build-tools) #### [macOS](https://book.arch.network/docs/quick-start/requirements#macos) xcode-select --install # Install Command Line Tools #### [Linux (Debian/Ubuntu)](https://book.arch.network/docs/quick-start/requirements#linux-debianubuntu) sudo apt-get update sudo apt-get install -y build-essential gcc-multilib jq ### [3\. Install Solana CLI](https://book.arch.network/docs/quick-start/requirements#3-install-solana-cli) sh -c "$(curl -sSfL https://release.solana.com/stable/install)" # Verify installation (should show 2.x.x or later) solana --version ### [4\. Install Arch Network CLI](https://book.arch.network/docs/quick-start/requirements#4-install-arch-network-cli) [### macOS - Apple Silicon\ \ Installation instructions for Apple Silicon Macs](https://book.arch.network/docs/quick-start/requirements#macos-apple-silicon) [### macOS - Intel\ \ Installation instructions for Intel Macs](https://book.arch.network/docs/quick-start/requirements#macos-intel) [### Linux - x86\_64\ \ Installation instructions for Linux x86\_64](https://book.arch.network/docs/quick-start/requirements#linux-x86_64) [### Linux - ARM64\ \ Installation instructions for Linux ARM64](https://book.arch.network/docs/quick-start/requirements#linux-arm64) #### [macOS - Apple Silicon](https://book.arch.network/docs/quick-start/requirements#macos---apple-silicon) curl -L -o cli https://github.com/Arch-Network/arch-node/releases/latest/download/cli-aarch64-apple-darwin chmod +x cli sudo mv cli /usr/local/bin/ #### [macOS - Intel](https://book.arch.network/docs/quick-start/requirements#macos---intel) curl -L -o cli https://github.com/Arch-Network/arch-node/releases/latest/download/cli-x86_64-apple-darwin chmod +x cli sudo mv cli /usr/local/bin/ #### [Linux - x86\_64](https://book.arch.network/docs/quick-start/requirements#linux---x86_64) curl -L -o cli https://github.com/Arch-Network/arch-node/releases/latest/download/cli-x86_64-unknown-linux-gnu chmod +x cli sudo mv cli /usr/local/bin/ #### [Linux - ARM64](https://book.arch.network/docs/quick-start/requirements#linux---arm64) curl -L -o cli https://github.com/Arch-Network/arch-node/releases/latest/download/cli-aarch64-unknown-linux-gnu chmod +x cli sudo mv cli /usr/local/bin/ Verify installation: cli --version [Docker Requirements](https://book.arch.network/docs/quick-start/requirements#docker-requirements) --------------------------------------------------------------------------------------------------- For running the complete Arch Network stack locally, you'll need Docker: ### [Install Docker](https://book.arch.network/docs/quick-start/requirements#install-docker) #### [macOS](https://book.arch.network/docs/quick-start/requirements#macos-1) * **Recommended**: [OrbStack](https://orbstack.dev/) - Lightweight and fast * **Alternative**: [Docker Desktop](https://www.docker.com/products/docker-desktop/) #### [Linux](https://book.arch.network/docs/quick-start/requirements#linux) # Ubuntu/Debian sudo apt-get update sudo apt-get install -y docker.io docker-compose sudo systemctl start docker sudo systemctl enable docker # Add your user to docker group sudo usermod -aG docker $USER # Log out and back in for changes to take effect #### [Windows](https://book.arch.network/docs/quick-start/requirements#windows) * [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop/) ### [Verify Docker Installation](https://book.arch.network/docs/quick-start/requirements#verify-docker-installation) docker --version docker-compose --version docker run hello-world [Development Environment Setup](https://book.arch.network/docs/quick-start/requirements#development-environment-setup) ----------------------------------------------------------------------------------------------------------------------- ### [VS Code (Recommended)](https://book.arch.network/docs/quick-start/requirements#vs-code-recommended) Install the following extensions: * **Rust Analyzer** - Rust language support * **Solana** - Solana program development * **GitLens** - Enhanced Git capabilities * **Thunder Client** - API testing * **Markdown All in One** - Markdown support ### [Terminal Setup](https://book.arch.network/docs/quick-start/requirements#terminal-setup) #### [macOS (iTerm2 + Oh My Zsh)](https://book.arch.network/docs/quick-start/requirements#macos-iterm2--oh-my-zsh) # Install iTerm2 brew install --cask iterm2 # Install Oh My Zsh sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" # Install useful plugins git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting #### [Linux (Terminator + Oh My Bash)](https://book.arch.network/docs/quick-start/requirements#linux-terminator--oh-my-bash) # Install Terminator sudo apt-get install terminator # Install Oh My Bash bash -c "$(curl -fsSL https://raw.githubusercontent.com/ohmybash/oh-my-bash/master/tools/install.sh)" [Network Requirements](https://book.arch.network/docs/quick-start/requirements#network-requirements) ----------------------------------------------------------------------------------------------------- ### [Port Configuration](https://book.arch.network/docs/quick-start/requirements#port-configuration) The following ports need to be available: | Service | Port | Description | | --- | --- | --- | | Bitcoin Core RPC | 18443 (regtest) / 18332 (testnet) | Bitcoin RPC interface | | Titan HTTP API | 8080 | Titan HTTP API | | Titan TCP API | 3030 | Titan TCP interface | | Arch Validator RPC | 9002 | Validator RPC interface | | Arch Validator P2P | 9003 | Peer-to-peer networking | ### [Firewall Configuration](https://book.arch.network/docs/quick-start/requirements#firewall-configuration) #### [macOS](https://book.arch.network/docs/quick-start/requirements#macos-2) # Allow incoming connections (if needed) sudo pfctl -f /etc/pf.conf #### [Linux (UFW)](https://book.arch.network/docs/quick-start/requirements#linux-ufw) # Allow specific ports sudo ufw allow 9002 sudo ufw allow 9003 sudo ufw allow 8080 sudo ufw allow 3030 [Troubleshooting](https://book.arch.network/docs/quick-start/requirements#troubleshooting) ------------------------------------------------------------------------------------------- ### [Solana Installation Issues](https://book.arch.network/docs/quick-start/requirements#solana-installation-issues) If you installed Rust through Homebrew and encounter `cargo-build-sbf` issues: 1. Remove existing Rust installation: rustup self uninstall 2. Perform clean Rust installation: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh 3. Reinstall Solana: sh -c "$(curl -sSfL https://release.solana.com/stable/install)" ### [Docker Issues](https://book.arch.network/docs/quick-start/requirements#docker-issues) **Docker daemon not running:** # macOS (Docker Desktop) open -a Docker # Linux sudo systemctl start docker **Permission denied:** # Add user to docker group sudo usermod -aG docker $USER # Log out and back in ### [Network Issues](https://book.arch.network/docs/quick-start/requirements#network-issues) **Port already in use:** # Find process using port lsof -i :9002 # Kill process kill -9 **Connection refused:** # Check if service is running curl http://localhost:9002/health # Check service logs arch-cli orchestrate logs [Performance Optimization](https://book.arch.network/docs/quick-start/requirements#performance-optimization) ------------------------------------------------------------------------------------------------------------- ### [System Tuning](https://book.arch.network/docs/quick-start/requirements#system-tuning) #### [Linux](https://book.arch.network/docs/quick-start/requirements#linux-1) # Increase file descriptor limits echo "* soft nofile 65536" | sudo tee -a /etc/security/limits.conf echo "* hard nofile 65536" | sudo tee -a /etc/security/limits.conf # Optimize network settings echo "net.core.rmem_max = 134217728" | sudo tee -a /etc/sysctl.conf echo "net.core.wmem_max = 134217728" | sudo tee -a /etc/sysctl.conf sudo sysctl -p #### [macOS](https://book.arch.network/docs/quick-start/requirements#macos-3) # Increase file descriptor limits sudo launchctl limit maxfiles 65536 200000 ### [Docker Optimization](https://book.arch.network/docs/quick-start/requirements#docker-optimization) # Increase Docker memory limit # In Docker Desktop: Settings > Resources > Memory > 8GB+ # Enable experimental features for better performance echo '{"experimental": true}' | sudo tee /etc/docker/daemon.json sudo systemctl restart docker [Verification Checklist](https://book.arch.network/docs/quick-start/requirements#verification-checklist) --------------------------------------------------------------------------------------------------------- Before proceeding with development, verify: * [ ] Rust is installed and working (`rustc --version`) * [ ] Solana CLI is installed (`solana --version`) * [ ] Arch CLI is installed (`arch-cli --version`) * [ ] Docker is running (`docker --version`) * [ ] All required ports are available * [ ] Development environment is configured * [ ] Network connectivity is working [Next Steps](https://book.arch.network/docs/quick-start/requirements#next-steps) --------------------------------------------------------------------------------- [### Quick Start Guide\ \ Get your first program running in 15 minutes](https://book.arch.network/docs/quick-start/quick-start) [### Validator Setup\ \ Set up a complete validator node](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) [### Writing Your First Program\ \ Learn to build Arch programs](https://book.arch.network/docs/development/writing-your-first-program) [Need Help?](https://book.arch.network/docs/quick-start/requirements#need-help) -------------------------------------------------------------------------------- [### Troubleshooting Guide\ \ Common issues and solutions](https://book.arch.network/docs/reference/troubleshooting) [### Discord Community\ \ Join our developer community](https://discord.gg/archnetwork) [### GitHub Issues\ \ Report bugs and request features](https://github.com/Arch-Network/arch-node/issues) [πŸš€ Quick Start Guide\ \ Get your first program running on Arch Network in under 15 minutes](https://book.arch.network/docs/quick-start/quick-start) [RPC Reference\ \ Next Page](https://book.arch.network/docs/reference/rpc) ### On this page [System Requirements](https://book.arch.network/docs/quick-start/requirements#system-requirements) [Hardware Requirements](https://book.arch.network/docs/quick-start/requirements#hardware-requirements) [Software Requirements](https://book.arch.network/docs/quick-start/requirements#software-requirements) [Installation Guide](https://book.arch.network/docs/quick-start/requirements#installation-guide) [1\. Install Rust](https://book.arch.network/docs/quick-start/requirements#1-install-rust) [2\. Install Build Tools](https://book.arch.network/docs/quick-start/requirements#2-install-build-tools) [macOS](https://book.arch.network/docs/quick-start/requirements#macos) [Linux (Debian/Ubuntu)](https://book.arch.network/docs/quick-start/requirements#linux-debianubuntu) [3\. Install Solana CLI](https://book.arch.network/docs/quick-start/requirements#3-install-solana-cli) [4\. Install Arch Network CLI](https://book.arch.network/docs/quick-start/requirements#4-install-arch-network-cli) [macOS - Apple Silicon](https://book.arch.network/docs/quick-start/requirements#macos---apple-silicon) [macOS - Intel](https://book.arch.network/docs/quick-start/requirements#macos---intel) [Linux - x86\_64](https://book.arch.network/docs/quick-start/requirements#linux---x86_64) [Linux - ARM64](https://book.arch.network/docs/quick-start/requirements#linux---arm64) [Docker Requirements](https://book.arch.network/docs/quick-start/requirements#docker-requirements) [Install Docker](https://book.arch.network/docs/quick-start/requirements#install-docker) [macOS](https://book.arch.network/docs/quick-start/requirements#macos-1) [Linux](https://book.arch.network/docs/quick-start/requirements#linux) [Windows](https://book.arch.network/docs/quick-start/requirements#windows) [Verify Docker Installation](https://book.arch.network/docs/quick-start/requirements#verify-docker-installation) [Development Environment Setup](https://book.arch.network/docs/quick-start/requirements#development-environment-setup) [VS Code (Recommended)](https://book.arch.network/docs/quick-start/requirements#vs-code-recommended) [Terminal Setup](https://book.arch.network/docs/quick-start/requirements#terminal-setup) [macOS (iTerm2 + Oh My Zsh)](https://book.arch.network/docs/quick-start/requirements#macos-iterm2--oh-my-zsh) [Linux (Terminator + Oh My Bash)](https://book.arch.network/docs/quick-start/requirements#linux-terminator--oh-my-bash) [Network Requirements](https://book.arch.network/docs/quick-start/requirements#network-requirements) [Port Configuration](https://book.arch.network/docs/quick-start/requirements#port-configuration) [Firewall Configuration](https://book.arch.network/docs/quick-start/requirements#firewall-configuration) [macOS](https://book.arch.network/docs/quick-start/requirements#macos-2) [Linux (UFW)](https://book.arch.network/docs/quick-start/requirements#linux-ufw) [Troubleshooting](https://book.arch.network/docs/quick-start/requirements#troubleshooting) [Solana Installation Issues](https://book.arch.network/docs/quick-start/requirements#solana-installation-issues) [Docker Issues](https://book.arch.network/docs/quick-start/requirements#docker-issues) [Network Issues](https://book.arch.network/docs/quick-start/requirements#network-issues) [Performance Optimization](https://book.arch.network/docs/quick-start/requirements#performance-optimization) [System Tuning](https://book.arch.network/docs/quick-start/requirements#system-tuning) [Linux](https://book.arch.network/docs/quick-start/requirements#linux-1) [macOS](https://book.arch.network/docs/quick-start/requirements#macos-3) [Docker Optimization](https://book.arch.network/docs/quick-start/requirements#docker-optimization) [Verification Checklist](https://book.arch.network/docs/quick-start/requirements#verification-checklist) [Next Steps](https://book.arch.network/docs/quick-start/requirements#next-steps) [Need Help?](https://book.arch.network/docs/quick-start/requirements#need-help) --- # RPC API Reference APIs and Tools RPC API Reference ================= Complete JSON-RPC API reference for interacting with Arch Network validator nodes The Arch Network provides a comprehensive JSON-RPC API for interacting with validator nodes. This API allows you to: * Query account information and balances * Submit transactions to the network * Retrieve block and transaction data * Monitor network state and readiness * Manage validator operations ::::note **RPC Method Availability**: For a complete list of which RPC methods are available in the `validator` vs `local_validator` crates, along with their correct parameter formats, see the RPC section below. :::: [API Endpoints](https://book.arch.network/docs/tools-apis/api-reference#api-endpoints) --------------------------------------------------------------------------------------- ### [Default Configuration](https://book.arch.network/docs/tools-apis/api-reference#default-configuration) * **Default Port**: `9001` for validator nodes, `9002` for local validators * **Endpoint URL**: `http://localhost:9002` (or your node's IP address) * **Protocol**: HTTP POST with JSON-RPC 2.0 ### [Request Format](https://book.arch.network/docs/tools-apis/api-reference#request-format) All RPC requests must be sent as HTTP `POST` requests with: * **Content-Type**: `application/json` * **JSON-RPC Version**: `"2.0"` { "jsonrpc": "2.0", "id": 1, "method": "method_name", "params": [/* parameters */] } ### [Response Format](https://book.arch.network/docs/tools-apis/api-reference#response-format) { "jsonrpc": "2.0", "id": 1, "result": {/* response data */} } [Available Methods](https://book.arch.network/docs/tools-apis/api-reference#available-methods) ----------------------------------------------------------------------------------------------- ### [Account Operations](https://book.arch.network/docs/tools-apis/api-reference#account-operations) * [`read_account_info`](https://book.arch.network/docs/tools-apis/api-reference#read_account_info) - Get account information * [`get_account_address`](https://book.arch.network/docs/tools-apis/api-reference#get_account_address) - Get Bitcoin address for account * [`get_program_accounts`](https://book.arch.network/docs/tools-apis/api-reference#get_program_accounts) - Query accounts by program ID * [`get_all_accounts`](https://book.arch.network/docs/tools-apis/api-reference#get_all_accounts) - Get all account public keys * [`get_multiple_accounts`](https://book.arch.network/docs/tools-apis/api-reference#get_multiple_accounts) - Get multiple accounts in one call ### [Transaction Operations](https://book.arch.network/docs/tools-apis/api-reference#transaction-operations) * [`send_transaction`](https://book.arch.network/docs/tools-apis/api-reference#send_transaction) - Submit a single transaction * [`send_transactions`](https://book.arch.network/docs/tools-apis/api-reference#send_transactions) - Submit multiple transactions * [`get_processed_transaction`](https://book.arch.network/docs/tools-apis/api-reference#get_processed_transaction) - Get transaction status and details * [`get_transaction_report`](https://book.arch.network/docs/tools-apis/api-reference#get_transaction_report) - Get detailed transaction processing report * [`request_airdrop`](https://book.arch.network/docs/tools-apis/api-reference#request_airdrop) - Request faucet airdrop to an address * [`create_account_with_faucet`](https://book.arch.network/docs/tools-apis/api-reference#create_account_with_faucet) - Build a faucet-funded create account tx * [`recent_transactions`](https://book.arch.network/docs/tools-apis/api-reference#recent_transactions) - List recent transactions * [`get_transactions_by_block`](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_block) - List transactions for a block * [`get_transactions_by_ids`](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_ids) - Fetch transactions by ids ### [Block Operations](https://book.arch.network/docs/tools-apis/api-reference#block-operations) * [`get_block`](https://book.arch.network/docs/tools-apis/api-reference#get_block) - Get block by hash * [`get_block_count`](https://book.arch.network/docs/tools-apis/api-reference#get_block_count) - Get current block count * [`get_block_hash`](https://book.arch.network/docs/tools-apis/api-reference#get_block_hash) - Get block hash by height * [`get_best_block_hash`](https://book.arch.network/docs/tools-apis/api-reference#get_best_block_hash) - Get latest block hash * [`get_best_finalized_block_hash`](https://book.arch.network/docs/tools-apis/api-reference#get_best_finalized_block_hash) - Get latest finalized block hash * [`get_block_by_height`](https://book.arch.network/docs/tools-apis/api-reference#get_block_by_height) - Get block by height ### [Network Operations](https://book.arch.network/docs/tools-apis/api-reference#network-operations) * [`is_node_ready`](https://book.arch.network/docs/tools-apis/api-reference#is_node_ready) - Check node readiness * [`get_network_pubkey`](https://book.arch.network/docs/tools-apis/api-reference#get_network_pubkey) - Get the network verifying key * [`check_pre_anchor_conflict`](https://book.arch.network/docs/tools-apis/api-reference#check_pre_anchor_conflict) - Check for pre-anchor conflicts ### [System Operations](https://book.arch.network/docs/tools-apis/api-reference#system-operations) * [`get_version`](https://book.arch.network/docs/tools-apis/api-reference#get_version) - Get node version information [Account Operations](https://book.arch.network/docs/tools-apis/api-reference#account-operations-1) --------------------------------------------------------------------------------------------------- ### [read\_account\_info](https://book.arch.network/docs/tools-apis/api-reference#read_account_info) Retrieves information for a specified account. **Parameters:** 1. `pubkey` - Account public key as a 32-byte array **Returns:** Account information object with `data`, `owner`, `utxo`, `is_executable`, and `tag` fields. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "read_account_info", "params": ["11111111111111111111111111111112"] }' ### [get\_account\_address](https://book.arch.network/docs/tools-apis/api-reference#get_account_address) Gets the Bitcoin address associated with an account. **Parameters:** 1. `pubkey` - Account public key as a 32-byte array **Returns:** Bitcoin address string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_account_address", "params": ["11111111111111111111111111111112"] }' ### [get\_program\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_program_accounts) Retrieves all accounts owned by a specific program. **Parameters:** 1. `program_id` - Program public key as a 32-byte array **Returns:** Array of account information objects. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_program_accounts", "params": ["AplToken111111111111111111111111"] }' ### [get\_multiple\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_multiple_accounts) Retrieves info for multiple accounts in one call. **Parameters:** 1. `pubkeys` - Array of account public keys (string-serialized) **Returns:** Array of account information objects. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_multiple_accounts", "params": [["", ""]] }' ### [get\_all\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_all_accounts) Lists all known account public keys. **Parameters:** None **Returns:** Array of public keys (hex strings). **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_all_accounts", "params": [] }' [Transaction Operations](https://book.arch.network/docs/tools-apis/api-reference#transaction-operations-1) ----------------------------------------------------------------------------------------------------------- ### [send\_transaction](https://book.arch.network/docs/tools-apis/api-reference#send_transaction) Submits a transaction to the network for processing. **Parameters:** 1. `transaction` - Base64-encoded transaction data **Returns:** Transaction signature string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "send_transaction", "params": ["base64_encoded_transaction_data"] }' ### [send\_transactions](https://book.arch.network/docs/tools-apis/api-reference#send_transactions) Submits multiple transactions to the network for processing in a single request. **Parameters:** 1. `transactions` - Array of base64-encoded transaction data **Returns:** Array of transaction signature strings. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "send_transactions", "params": [["base64_tx_1","base64_tx_2"]] }' ### [get\_processed\_transaction](https://book.arch.network/docs/tools-apis/api-reference#get_processed_transaction) Retrieves the status and details of a processed transaction. **Parameters:** 1. `signature` - Transaction signature string **Returns:** Transaction status and details object. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_processed_transaction", "params": ["transaction_signature_here"] }' ### [get\_transaction\_report](https://book.arch.network/docs/tools-apis/api-reference#get_transaction_report) Retrieves a detailed processing report for a transaction. **Parameters:** 1. `txid` - Transaction id (hash) string **Returns:** Stringified report details. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_transaction_report", "params": [""] }' ### [get\_arch\_txid\_from\_btc\_txid](https://book.arch.network/docs/tools-apis/api-reference#get_arch_txid_from_btc_txid) Looks up the Arch transaction id corresponding to a given Bitcoin txid. **Parameters:** 1. `btc_txid` - Bitcoin transaction id (string) **Returns:** Arch txid string or null if not found. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_arch_txid_from_btc_txid", "params": [""] }' ### [get\_latest\_tx\_using\_account](https://book.arch.network/docs/tools-apis/api-reference#get_latest_tx_using_account) Retrieves the most recent Arch txid that touched the specified account. **Parameters:** 1. `account_pubkey` - Account public key (hex string) **Returns:** Arch txid string or null if none found. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_latest_tx_using_account", "params": [""] }' ### [request\_airdrop](https://book.arch.network/docs/tools-apis/api-reference#request_airdrop) Requests 1\_000\_000\_000 lamports from the local faucet to the specified account. **Parameters:** 1. `pubkey` - Recipient account public key (string-serialized) **Returns:** Transaction signature string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "request_airdrop", "params": [""] }' ### [create\_account\_with\_faucet](https://book.arch.network/docs/tools-apis/api-reference#create_account_with_faucet) Builds a signed RuntimeTransaction from the faucet to create a new account for the provided public key. Note: This returns a transaction object; submit it using `send_transaction`. **Parameters:** 1. `pubkey` - New account public key (string-serialized) **Returns:** A transaction object with `version`, `signatures`, and `message` fields. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "create_account_with_faucet", "params": [""] }' ### [recent\_transactions](https://book.arch.network/docs/tools-apis/api-reference#recent_transactions) Retrieves most recent transactions with optional pagination and account filter. **Parameters (object):** * `limit` (optional, number) * `offset` (optional, number) * `account` (optional, string-serialized pubkey) **Returns:** Array of processed transactions. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "recent_transactions", "params": [{"limit": 10}] }' ### [get\_transactions\_by\_block](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_block) Lists transactions for a specific block with optional pagination and account filter. **Parameters (object):** * `block_hash` (string, required) * `limit` (optional, number) * `offset` (optional, number) * `account` (optional, string-serialized pubkey) **Returns:** Array of processed transactions. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_transactions_by_block", "params": [{"block_hash": "", "limit": 25}] }' ### [get\_transactions\_by\_ids](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_ids) Fetches transactions by their txids. **Parameters (object):** * `txids` (array of strings, required) **Returns:** Array of processed transactions. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_transactions_by_ids", "params": [{"txids": ["", ""]}] }' [Block Operations](https://book.arch.network/docs/tools-apis/api-reference#block-operations-1) ----------------------------------------------------------------------------------------------- ### [get\_block](https://book.arch.network/docs/tools-apis/api-reference#get_block) Retrieves block information by block hash. **Parameters:** 1. `block_hash` - Block hash as a 32-byte array **Returns:** Block information object. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_block", "params": ["block_hash_here"] }' ### [get\_block\_count](https://book.arch.network/docs/tools-apis/api-reference#get_block_count) Gets the current block count (height) of the blockchain. **Parameters:** None **Returns:** Block count as a number. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_block_count", "params": [] }' ### [get\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_block_hash) Retrieves the block hash for a given block height. **Parameters:** 1. `block_height` - Block height (number) **Returns:** Block hash string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_block_hash", "params": [12345] }' ### [get\_block\_by\_height](https://book.arch.network/docs/tools-apis/api-reference#get_block_by_height) Retrieves block information by block height. **Parameters:** 1. `block_height` - Block height (number) Optionally, a second parameter may request the full block object. **Returns:** Block information object. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_block_by_height", "params": [12345] }' ### [get\_best\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_best_block_hash) Gets the latest (tip) block hash. **Parameters:** None **Returns:** Block hash string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_best_block_hash", "params": [] }' ### [get\_best\_finalized\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_best_finalized_block_hash) Gets the latest finalized block hash. **Parameters:** None **Returns:** Block hash string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_best_finalized_block_hash", "params": [] }' [Network Operations](https://book.arch.network/docs/tools-apis/api-reference#network-operations-1) --------------------------------------------------------------------------------------------------- ### [is\_node\_ready](https://book.arch.network/docs/tools-apis/api-reference#is_node_ready) Checks if the node is ready to process requests. **Parameters:** None **Returns:** Boolean indicating node readiness. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "is_node_ready", "params": [] }' ### [get\_peers](https://book.arch.network/docs/tools-apis/api-reference#get_peers) Retrieves information about connected network peers. **Parameters:** None **Returns:** Array of peer information objects. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_peers", "params": [] }' ### [get\_network\_pubkey](https://book.arch.network/docs/tools-apis/api-reference#get_network_pubkey) Returns the validator's network verifying key (group x-pubkey). **Parameters:** None **Returns:** Hex-encoded x-only public key string. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_network_pubkey", "params": [] }' ### [check\_pre\_anchor\_conflict](https://book.arch.network/docs/tools-apis/api-reference#check_pre_anchor_conflict) Checks for pre-anchor conflicts for a set of accounts. **Parameters:** 1. `accounts` - Array of account public keys (string-serialized) **Returns:** Boolean indicating whether a conflict exists. **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "check_pre_anchor_conflict", "params": [["", ""]] }' [System Operations](https://book.arch.network/docs/tools-apis/api-reference#system-operations-1) ------------------------------------------------------------------------------------------------- ### [get\_version](https://book.arch.network/docs/tools-apis/api-reference#get_version) Retrieves node version information. **Parameters:** None **Returns:** Object containing `version` and `feature_set` (optional). **Example:** curl -X POST http://localhost:9002 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "get_version", "params": [] }' [Error Handling](https://book.arch.network/docs/tools-apis/api-reference#error-handling) ----------------------------------------------------------------------------------------- ### [Error Response Format](https://book.arch.network/docs/tools-apis/api-reference#error-response-format) { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Invalid params", "data": "Additional error details" } } ### [Common Error Codes](https://book.arch.network/docs/tools-apis/api-reference#common-error-codes) * `-32600`: Invalid Request * `-32601`: Method not found * `-32602`: Invalid params * `-32603`: Internal error * `-32000`: Server error (custom) [SDK Integration](https://book.arch.network/docs/tools-apis/api-reference#sdk-integration) ------------------------------------------------------------------------------------------- ### [TypeScript SDK](https://book.arch.network/docs/tools-apis/api-reference#typescript-sdk) import { Connection } from '@saturnbtcio/arch-sdk'; const connection = new Connection('http://localhost:9002'); // Get account info const accountInfo = await connection.getAccountInfo(publicKey); // Send transaction const signature = await connection.sendTransaction(transaction); ### [Rust SDK](https://book.arch.network/docs/tools-apis/api-reference#rust-sdk) use arch_sdk::{Connection, Pubkey}; #[tokio::main] async fn main() -> Result<(), Box> { let connection = Connection::new("http://localhost:9002"); // Get account info let account_info = connection.get_account_info(&public_key).await?; // Send transaction let signature = connection.send_transaction(&transaction).await?; Ok(()) } [Best Practices](https://book.arch.network/docs/tools-apis/api-reference#best-practices) ----------------------------------------------------------------------------------------- ### [1\. Connection Management](https://book.arch.network/docs/tools-apis/api-reference#1-connection-management) * Use connection pooling for high-frequency requests * Implement proper timeout handling * Monitor connection health ### [2\. Error Handling](https://book.arch.network/docs/tools-apis/api-reference#2-error-handling) * Always check for RPC errors * Implement retry logic for transient failures * Log errors for debugging ### [3\. Performance](https://book.arch.network/docs/tools-apis/api-reference#3-performance) * Batch multiple requests when possible * Use appropriate polling intervals * Cache frequently accessed data ### [4\. Security](https://book.arch.network/docs/tools-apis/api-reference#4-security) * Use HTTPS in production * Implement proper authentication * Validate all input parameters [Next Steps](https://book.arch.network/docs/tools-apis/api-reference#next-steps) --------------------------------------------------------------------------------- [### SDK Reference\ \ Check which methods are available in different environments](https://book.arch.network/docs/tools-apis/sdk) [### SDK Reference\ \ Learn to use the SDKs for easier integration](https://book.arch.network/docs/sdk/sdk) [### CLI Reference\ \ Use the CLI for common operations](https://book.arch.network/docs/tools-apis/arch-cli-reference) [### Examples\ \ Explore example implementations](https://github.com/Arch-Network/arch-examples) [Resources](https://book.arch.network/docs/tools-apis/api-reference#resources) ------------------------------------------------------------------------------- [### Arch Network Repository\ \ Source code and issues](https://github.com/Arch-Network/arch-network) [### TypeScript SDK\ \ TypeScript SDK for easier integration](https://github.com/saturnbtc/arch-typescript-sdk) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [### Arch Examples\ \ Example applications and programs](https://github.com/Arch-Network/arch-examples) [Network Architecture\ \ Understanding Arch Network's distributed system architecture and node interactions](https://book.arch.network/docs/setup-infrastructure/network-architecture) [Arch CLI Reference Guide\ \ Complete reference for all Arch Network CLI commands and options](https://book.arch.network/docs/tools-apis/arch-cli-reference) ### On this page [API Endpoints](https://book.arch.network/docs/tools-apis/api-reference#api-endpoints) [Default Configuration](https://book.arch.network/docs/tools-apis/api-reference#default-configuration) [Request Format](https://book.arch.network/docs/tools-apis/api-reference#request-format) [Response Format](https://book.arch.network/docs/tools-apis/api-reference#response-format) [Available Methods](https://book.arch.network/docs/tools-apis/api-reference#available-methods) [Account Operations](https://book.arch.network/docs/tools-apis/api-reference#account-operations) [Transaction Operations](https://book.arch.network/docs/tools-apis/api-reference#transaction-operations) [Block Operations](https://book.arch.network/docs/tools-apis/api-reference#block-operations) [Network Operations](https://book.arch.network/docs/tools-apis/api-reference#network-operations) [System Operations](https://book.arch.network/docs/tools-apis/api-reference#system-operations) [Account Operations](https://book.arch.network/docs/tools-apis/api-reference#account-operations-1) [read\_account\_info](https://book.arch.network/docs/tools-apis/api-reference#read_account_info) [get\_account\_address](https://book.arch.network/docs/tools-apis/api-reference#get_account_address) [get\_program\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_program_accounts) [get\_multiple\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_multiple_accounts) [get\_all\_accounts](https://book.arch.network/docs/tools-apis/api-reference#get_all_accounts) [Transaction Operations](https://book.arch.network/docs/tools-apis/api-reference#transaction-operations-1) [send\_transaction](https://book.arch.network/docs/tools-apis/api-reference#send_transaction) [send\_transactions](https://book.arch.network/docs/tools-apis/api-reference#send_transactions) [get\_processed\_transaction](https://book.arch.network/docs/tools-apis/api-reference#get_processed_transaction) [get\_transaction\_report](https://book.arch.network/docs/tools-apis/api-reference#get_transaction_report) [get\_arch\_txid\_from\_btc\_txid](https://book.arch.network/docs/tools-apis/api-reference#get_arch_txid_from_btc_txid) [get\_latest\_tx\_using\_account](https://book.arch.network/docs/tools-apis/api-reference#get_latest_tx_using_account) [request\_airdrop](https://book.arch.network/docs/tools-apis/api-reference#request_airdrop) [create\_account\_with\_faucet](https://book.arch.network/docs/tools-apis/api-reference#create_account_with_faucet) [recent\_transactions](https://book.arch.network/docs/tools-apis/api-reference#recent_transactions) [get\_transactions\_by\_block](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_block) [get\_transactions\_by\_ids](https://book.arch.network/docs/tools-apis/api-reference#get_transactions_by_ids) [Block Operations](https://book.arch.network/docs/tools-apis/api-reference#block-operations-1) [get\_block](https://book.arch.network/docs/tools-apis/api-reference#get_block) [get\_block\_count](https://book.arch.network/docs/tools-apis/api-reference#get_block_count) [get\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_block_hash) [get\_block\_by\_height](https://book.arch.network/docs/tools-apis/api-reference#get_block_by_height) [get\_best\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_best_block_hash) [get\_best\_finalized\_block\_hash](https://book.arch.network/docs/tools-apis/api-reference#get_best_finalized_block_hash) [Network Operations](https://book.arch.network/docs/tools-apis/api-reference#network-operations-1) [is\_node\_ready](https://book.arch.network/docs/tools-apis/api-reference#is_node_ready) [get\_peers](https://book.arch.network/docs/tools-apis/api-reference#get_peers) [get\_network\_pubkey](https://book.arch.network/docs/tools-apis/api-reference#get_network_pubkey) [check\_pre\_anchor\_conflict](https://book.arch.network/docs/tools-apis/api-reference#check_pre_anchor_conflict) [System Operations](https://book.arch.network/docs/tools-apis/api-reference#system-operations-1) [get\_version](https://book.arch.network/docs/tools-apis/api-reference#get_version) [Error Handling](https://book.arch.network/docs/tools-apis/api-reference#error-handling) [Error Response Format](https://book.arch.network/docs/tools-apis/api-reference#error-response-format) [Common Error Codes](https://book.arch.network/docs/tools-apis/api-reference#common-error-codes) [SDK Integration](https://book.arch.network/docs/tools-apis/api-reference#sdk-integration) [TypeScript SDK](https://book.arch.network/docs/tools-apis/api-reference#typescript-sdk) [Rust SDK](https://book.arch.network/docs/tools-apis/api-reference#rust-sdk) [Best Practices](https://book.arch.network/docs/tools-apis/api-reference#best-practices) [1\. Connection Management](https://book.arch.network/docs/tools-apis/api-reference#1-connection-management) [2\. Error Handling](https://book.arch.network/docs/tools-apis/api-reference#2-error-handling) [3\. Performance](https://book.arch.network/docs/tools-apis/api-reference#3-performance) [4\. Security](https://book.arch.network/docs/tools-apis/api-reference#4-security) [Next Steps](https://book.arch.network/docs/tools-apis/api-reference#next-steps) [Resources](https://book.arch.network/docs/tools-apis/api-reference#resources) --- # Introduction to the Arch Program Library (APL) APL (Arch Program Library) Introduction to the Arch Program Library (APL) ============================================== A collection of on-chain programs providing fundamental building blocks for Arch Network dApps The Arch Program Library (APL) is a collection of on-chain programs targeting the Arch Network blockchain. These programs serve as fundamental building blocks for developing decentralized applications (dApps) on Arch Network. The APL programs are thoroughly tested and provide developers with reliable and secure components for their applications. [Available Programs](https://book.arch.network/docs/apl/introduction#available-programs) ----------------------------------------------------------------------------------------- The APL currently includes the following core programs: ### [Token Program](https://book.arch.network/docs/apl/introduction#token-program) The foundation for creating and managing fungible tokens on Arch Network. It provides a robust implementation for: * Token creation and management * Account management * Transfer operations * Delegation capabilities * Multisignature support ### [Associated Token Account Program](https://book.arch.network/docs/apl/introduction#associated-token-account-program) A program that standardizes the creation and management of token accounts: * Deterministic account address derivation * Simplified account management * Reduced transaction complexity [Design Philosophy](https://book.arch.network/docs/apl/introduction#design-philosophy) --------------------------------------------------------------------------------------- The APL is designed with the following principles: 1. **Security First** * Comprehensive security audits * Battle-tested implementations * Conservative upgrade approach 2. **Composability** * Programs designed to work together * Standardized interfaces * Clear dependencies 3. **Performance** * Optimized for Arch Network's architecture * Efficient resource utilization * Scalable implementations 4. **Developer Experience** * Clear documentation * Example implementations * Testing utilities [Getting Started](https://book.arch.network/docs/apl/introduction#getting-started) ----------------------------------------------------------------------------------- To start building with APL: 1. Familiarize yourself with the [Arch Network architecture](https://book.arch.network/docs/setup-infrastructure/architecture) 2. Review the documentation for your program of interest 3. Check out the example implementations 4. Use the testing utilities to validate your integration [Contributing](https://book.arch.network/docs/apl/introduction#contributing) ----------------------------------------------------------------------------- The APL is an open-source project and welcomes contributions from the community. To contribute: 1. Review the contribution guidelines 2. Join the developer community 3. Submit proposals for new features 4. Help improve documentation 5. Report and fix bugs [Support](https://book.arch.network/docs/apl/introduction#support) ------------------------------------------------------------------- For support with APL: [### Join Discord\ \ Join the developer community](https://discord.gg/archnetwork) [### GitHub Issues\ \ Submit issues and feature requests](https://github.com/Arch-Network/arch-network/issues) [### Documentation\ \ Check the FAQ and troubleshooting guides](https://book.arch.network/docs) [Future Development](https://book.arch.network/docs/apl/introduction#future-development) ----------------------------------------------------------------------------------------- The APL is continuously evolving with new programs and improvements being added. Some areas of ongoing development include: * Advanced token standards * DeFi primitives (including AMM and Swap functionality) * Cross-chain bridges * Privacy-preserving features Stay connected with the community to learn about new developments and opportunities to contribute to the ecosystem. [Program Overview](https://book.arch.network/docs/apl/introduction#program-overview) ------------------------------------------------------------------------------------- [### Token Program\ \ Create and manage fungible tokens with full feature support](https://book.arch.network/docs/APL/token-program) [### Associated Token Account\ \ Standardized token account creation and management](https://book.arch.network/docs/APL/associated-token-account) [Associated Token Account Program\ \ Complete guide to the APL Associated Token Account Program for deterministic token account management](https://book.arch.network/docs/apl/associated-token-account) [APL Token Program\ \ Complete reference for the Arch Program Library Token Program - creating and managing fungible tokens](https://book.arch.network/docs/apl/token-program) ### On this page [Available Programs](https://book.arch.network/docs/apl/introduction#available-programs) [Token Program](https://book.arch.network/docs/apl/introduction#token-program) [Associated Token Account Program](https://book.arch.network/docs/apl/introduction#associated-token-account-program) [Design Philosophy](https://book.arch.network/docs/apl/introduction#design-philosophy) [Getting Started](https://book.arch.network/docs/apl/introduction#getting-started) [Contributing](https://book.arch.network/docs/apl/introduction#contributing) [Support](https://book.arch.network/docs/apl/introduction#support) [Future Development](https://book.arch.network/docs/apl/introduction#future-development) [Program Overview](https://book.arch.network/docs/apl/introduction#program-overview) --- # Writing Your First Arch Program Development Writing Your First Arch Program =============================== A comprehensive guide to creating your first Arch program from scratch with a complete counter example This comprehensive guide walks you through creating your first Arch program from scratch. We'll build a feature-rich counter program that demonstrates the complete development workflow and all essential concepts you need for building production-ready Arch Network applications. [What You'll Build](https://book.arch.network/docs/development/writing-your-first-program#what-youll-build) ------------------------------------------------------------------------------------------------------------ By the end of this guide, you'll have created a complete counter program that: * Manages state in program accounts * Handles multiple instruction types * Integrates with Bitcoin transactions * Includes comprehensive error handling * Provides extensive testing coverage * Follows security best practices [Prerequisites](https://book.arch.network/docs/development/writing-your-first-program#prerequisites) ----------------------------------------------------------------------------------------------------- Before starting, ensure you have: * **Rust 1.70+** and Cargo installed ([Install Rust](https://rustup.rs/) ) * **Solana CLI 2.0+** - [Install Guide](https://docs.solana.com/cli/install-solana-cli-tools) * **Arch Network CLI** - [Download Latest](https://github.com/Arch-Network/arch-node/releases/latest) * **Running validator** (see [Validator Setup Guide](https://book.arch.network/docs/setup-infrastructure/bitcoin-and-titan-setup) ) * **Basic Rust knowledge** and understanding of [Arch concepts](https://book.arch.network/docs/setup-infrastructure/architecture) [Step 1: Project Setup](https://book.arch.network/docs/development/writing-your-first-program#step-1-project-setup) -------------------------------------------------------------------------------------------------------------------- ### [1.1 Create Project Structure](https://book.arch.network/docs/development/writing-your-first-program#11-create-project-structure) # Create project directory mkdir my-counter-program cd my-counter-program # Create program directory mkdir program cd program # Initialize Rust library cargo init --lib ### [1.2 Configure Dependencies](https://book.arch.network/docs/development/writing-your-first-program#12-configure-dependencies) Create a proper `Cargo.toml`: **program/Cargo.toml** [package] name = "my_counter_program" version = "0.1.0" edition = "2021" [dependencies] arch_program = "0.5.4" borsh = { version = "1.5.1", features = ["derive"] } [lib] crate-type = ["cdylib", "lib"] [workspace] ### [1.3 Project Structure](https://book.arch.network/docs/development/writing-your-first-program#13-project-structure) Your project should look like this: my-counter-program/ β”œβ”€β”€ program/ β”‚ β”œβ”€β”€ src/ β”‚ β”‚ └── lib.rs β”‚ └── Cargo.toml β”œβ”€β”€ client/ # We'll add this later └── tests/ # We'll add this later [Step 2: Define Program Data Structures](https://book.arch.network/docs/development/writing-your-first-program#step-2-define-program-data-structures) ------------------------------------------------------------------------------------------------------------------------------------------------------ Create comprehensive data structures for your program: **program/src/lib.rs** use arch_program::{ account::AccountInfo, bitcoin::{self, absolute::LockTime, transaction::Version, Transaction}, entrypoint, helper::add_state_transition, input_to_sign::InputToSign, msg, program::{next_account_info, set_transaction_to_sign}, program_error::ProgramError, pubkey::Pubkey, transaction_to_sign::TransactionToSign, }; use borsh::{BorshDeserialize, BorshSerialize}; /// Counter program state stored in accounts #[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq)] pub struct CounterAccount { /// Current counter value pub count: i64, /// Who created this counter pub owner: Pubkey, /// When this counter was created pub created_at: i64, /// Last time the counter was updated pub last_updated: i64, /// Whether this counter is active pub is_active: bool, } /// Instructions that this program can handle #[derive(BorshSerialize, BorshDeserialize, Debug, Clone)] pub enum CounterInstruction { /// Initialize a new counter Initialize { initial_value: i64, }, /// Increment the counter by a specified amount Increment { amount: i64, }, /// Decrement the counter by a specified amount Decrement { amount: i64, }, /// Reset the counter to zero Reset, /// Transfer ownership of the counter TransferOwnership { new_owner: Pubkey, }, /// Deactivate the counter Deactivate, /// Reactivate the counter Reactivate, } /// Program errors #[derive(Debug)] pub enum CounterError { InvalidInstruction, InvalidAccount, Unauthorized, CounterOverflow, CounterUnderflow, CounterInactive, InvalidOwner, } impl From for ProgramError { fn from(e: CounterError) -> Self { ProgramError::Custom(e as u32) } } [Step 3: Implement Program Logic](https://book.arch.network/docs/development/writing-your-first-program#step-3-implement-program-logic) ---------------------------------------------------------------------------------------------------------------------------------------- Add the core program implementation: /// Process a single instruction pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { msg!("Counter program entry point"); // Parse the instruction let instruction = CounterInstruction::try_from_slice(instruction_data) .map_err(|_| CounterError::InvalidInstruction)?; // Get account iterator let accounts_iter = &mut accounts.iter(); let counter_account = next_account_info(accounts_iter)?; let owner_account = next_account_info(accounts_iter)?; // Verify the account is owned by this program if counter_account.owner != program_id { return Err(CounterError::InvalidAccount.into()); } // Process the instruction match instruction { CounterInstruction::Initialize { initial_value } => { process_initialize(counter_account, owner_account, initial_value) } CounterInstruction::Increment { amount } => { process_increment(counter_account, owner_account, amount) } CounterInstruction::Decrement { amount } => { process_decrement(counter_account, owner_account, amount) } CounterInstruction::Reset => { process_reset(counter_account, owner_account) } CounterInstruction::TransferOwnership { new_owner } => { process_transfer_ownership(counter_account, owner_account, &new_owner) } CounterInstruction::Deactivate => { process_deactivate(counter_account, owner_account) } CounterInstruction::Reactivate => { process_reactivate(counter_account, owner_account) } } } /// Initialize a new counter fn process_initialize( counter_account: &AccountInfo, owner_account: &AccountInfo, initial_value: i64, ) -> Result<(), ProgramError> { msg!("Initializing counter with value: {}", initial_value); // Check if account is already initialized if counter_account.data_len() > 0 { return Err(CounterError::InvalidAccount.into()); } // Create new counter account let counter = CounterAccount { count: initial_value, owner: *owner_account.key, created_at: get_current_timestamp(), last_updated: get_current_timestamp(), is_active: true, }; // Serialize and store the counter let serialized = counter.try_to_vec() .map_err(|_| ProgramError::InvalidAccountData)?; counter_account.try_borrow_mut_data()?[..serialized.len()].copy_from_slice(&serialized); msg!("Counter initialized successfully"); Ok(()) } /// Increment the counter fn process_increment( counter_account: &AccountInfo, owner_account: &AccountInfo, amount: i64, ) -> Result<(), ProgramError> { msg!("Incrementing counter by: {}", amount); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; verify_active(&counter)?; // Check for overflow if counter.count > i64::MAX - amount { return Err(CounterError::CounterOverflow.into()); } // Update counter counter.count += amount; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Counter incremented to: {}", counter.count); Ok(()) } /// Decrement the counter fn process_decrement( counter_account: &AccountInfo, owner_account: &AccountInfo, amount: i64, ) -> Result<(), ProgramError> { msg!("Decrementing counter by: {}", amount); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; verify_active(&counter)?; // Check for underflow if counter.count < amount { return Err(CounterError::CounterUnderflow.into()); } // Update counter counter.count -= amount; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Counter decremented to: {}", counter.count); Ok(()) } /// Reset the counter to zero fn process_reset( counter_account: &AccountInfo, owner_account: &AccountInfo, ) -> Result<(), ProgramError> { msg!("Resetting counter"); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; verify_active(&counter)?; // Reset counter counter.count = 0; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Counter reset to: {}", counter.count); Ok(()) } /// Transfer ownership of the counter fn process_transfer_ownership( counter_account: &AccountInfo, owner_account: &AccountInfo, new_owner: &Pubkey, ) -> Result<(), ProgramError> { msg!("Transferring ownership to: {}", new_owner); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; // Update owner counter.owner = *new_owner; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Ownership transferred successfully"); Ok(()) } /// Deactivate the counter fn process_deactivate( counter_account: &AccountInfo, owner_account: &AccountInfo, ) -> Result<(), ProgramError> { msg!("Deactivating counter"); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; // Deactivate counter counter.is_active = false; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Counter deactivated"); Ok(()) } /// Reactivate the counter fn process_reactivate( counter_account: &AccountInfo, owner_account: &AccountInfo, ) -> Result<(), ProgramError> { msg!("Reactivating counter"); // Load and verify counter let mut counter = load_counter(counter_account)?; verify_owner(&counter, owner_account)?; // Reactivate counter counter.is_active = true; counter.last_updated = get_current_timestamp(); // Save updated counter save_counter(counter_account, &counter)?; msg!("Counter reactivated"); Ok(()) } [Step 4: Helper Functions](https://book.arch.network/docs/development/writing-your-first-program#step-4-helper-functions) -------------------------------------------------------------------------------------------------------------------------- Add utility functions for common operations: /// Load a counter from account data fn load_counter(account: &AccountInfo) -> Result { let data = account.try_borrow_data()?; CounterAccount::try_from_slice(&data) .map_err(|_| ProgramError::InvalidAccountData) } /// Save a counter to account data fn save_counter(account: &AccountInfo, counter: &CounterAccount) -> Result<(), ProgramError> { let serialized = counter.try_to_vec() .map_err(|_| ProgramError::InvalidAccountData)?; let mut data = account.try_borrow_mut_data()?; data[..serialized.len()].copy_from_slice(&serialized); Ok(()) } /// Verify that the account is the owner fn verify_owner(counter: &CounterAccount, owner_account: &AccountInfo) -> Result<(), ProgramError> { if counter.owner != *owner_account.key { return Err(CounterError::Unauthorized.into()); } Ok(()) } /// Verify that the counter is active fn verify_active(counter: &CounterAccount) -> Result<(), ProgramError> { if !counter.is_active { return Err(CounterError::CounterInactive.into()); } Ok(()) } /// Get current timestamp (simplified for demo) fn get_current_timestamp() -> i64 { // In a real implementation, you'd get this from the system // For now, we'll use a placeholder 1234567890 } [Step 5: Program Entry Point](https://book.arch.network/docs/development/writing-your-first-program#step-5-program-entry-point) -------------------------------------------------------------------------------------------------------------------------------- Add the program entry point: // Declare the program's entry point entrypoint!(process_instruction); [Step 6: Build and Deploy](https://book.arch.network/docs/development/writing-your-first-program#step-6-build-and-deploy) -------------------------------------------------------------------------------------------------------------------------- ### [6.1 Build the Program](https://book.arch.network/docs/development/writing-your-first-program#61-build-the-program) # Build the program cargo build-sbf # Check the build output ls -la target/deploy/ ### [6.2 Deploy to Local Network](https://book.arch.network/docs/development/writing-your-first-program#62-deploy-to-local-network) # Deploy the program arch-cli deploy target/deploy/my_counter_program.so # Note the program ID for later use [Step 7: Create a Client](https://book.arch.network/docs/development/writing-your-first-program#step-7-create-a-client) ------------------------------------------------------------------------------------------------------------------------ Create a client to interact with your program: **client/Cargo.toml** [package] name = "counter-client" version = "0.1.0" edition = "2021" [dependencies] arch_program = "0.5.4" borsh = { version = "1.5.1", features = ["derive"] } solana-client = "1.17" solana-sdk = "1.17" **client/src/main.rs** use arch_program::{ instruction::{AccountMeta, Instruction}, pubkey::Pubkey, system_instruction, }; use borsh::{BorshDeserialize, BorshSerialize}; use solana_client::rpc_client::RpcClient; use solana_sdk::{ signature::{Keypair, Signer}, transaction::Transaction, }; // Import your program types use my_counter_program::{CounterAccount, CounterInstruction}; fn main() -> Result<(), Box> { // Connect to local validator let client = RpcClient::new("http://localhost:9002".to_string()); // Create keypairs let payer = Keypair::new(); let counter_keypair = Keypair::new(); // Airdrop some lamports to the payer client.request_airdrop(&payer.pubkey(), 1_000_000_000)?; // Create counter account let space = std::mem::size_of::(); let create_account_ix = system_instruction::create_account( &payer.pubkey(), &counter_keypair.pubkey(), 1_000_000, // rent space as u64, &program_id(), // Your program ID ); // Initialize counter instruction let init_ix = Instruction { program_id: program_id(), accounts: vec![\ AccountMeta::new(counter_keypair.pubkey(), false),\ AccountMeta::new_readonly(payer.pubkey(), true),\ ], data: CounterInstruction::Initialize { initial_value: 42 } .try_to_vec()?, }; // Create and send transaction let mut transaction = Transaction::new_with_payer( &[create_account_ix, init_ix], Some(&payer.pubkey()), ); let recent_blockhash = client.get_latest_blockhash()?; transaction.sign(&[&payer, &counter_keypair], recent_blockhash); client.send_and_confirm_transaction(&transaction)?; println!("Counter initialized successfully!"); // Read the counter state let account_data = client.get_account_data(&counter_keypair.pubkey())?; let counter: CounterAccount = CounterAccount::try_from_slice(&account_data)?; println!("Counter value: {}", counter.count); println!("Owner: {}", counter.owner); println!("Created at: {}", counter.created_at); Ok(()) } fn program_id() -> Pubkey { // Replace with your actual program ID "YourProgramIdHere".parse().unwrap() } [Step 8: Testing](https://book.arch.network/docs/development/writing-your-first-program#step-8-testing) -------------------------------------------------------------------------------------------------------- Create comprehensive tests for your program: **tests/integration\_tests.rs** use arch_program::{ account::AccountInfo, program_error::ProgramError, pubkey::Pubkey, }; use my_counter_program::{ process_instruction, CounterAccount, CounterInstruction, CounterError, }; #[test] fn test_initialize_counter() { // Test initialization logic let program_id = Pubkey::new_unique(); let owner = Pubkey::new_unique(); // Create mock accounts let mut counter_data = vec![0u8; 1000]; let counter_account = AccountInfo::new( &Pubkey::new_unique(), false, true, &mut counter_data, &program_id, &Pubkey::new_unique(), false, 0, ); let owner_account = AccountInfo::new( &owner, true, false, &mut vec![], &Pubkey::new_unique(), &Pubkey::new_unique(), false, 0, ); let accounts = vec![counter_account, owner_account]; let instruction = CounterInstruction::Initialize { initial_value: 100 }; let instruction_data = instruction.try_to_vec().unwrap(); // Process instruction let result = process_instruction(&program_id, &accounts, &instruction_data); assert!(result.is_ok()); // Verify counter was initialized let counter: CounterAccount = CounterAccount::try_from_slice(&counter_data[..100]).unwrap(); assert_eq!(counter.count, 100); assert_eq!(counter.owner, owner); assert!(counter.is_active); } #[test] fn test_increment_counter() { // Test increment logic // Similar structure to above test } #[test] fn test_unauthorized_access() { // Test that only the owner can modify the counter } #[test] fn test_overflow_protection() { // Test overflow protection } #[test] fn test_inactive_counter() { // Test that inactive counters can't be modified } [Step 9: Advanced Features](https://book.arch.network/docs/development/writing-your-first-program#step-9-advanced-features) ---------------------------------------------------------------------------------------------------------------------------- ### [9.1 Bitcoin Integration](https://book.arch.network/docs/development/writing-your-first-program#91-bitcoin-integration) Add Bitcoin transaction support: use arch_program::{ bitcoin::{Transaction, TxIn, TxOut}, helper::add_state_transition, input_to_sign::InputToSign, transaction_to_sign::TransactionToSign, }; /// Process a Bitcoin transaction fn process_bitcoin_transaction( counter_account: &AccountInfo, bitcoin_tx: &Transaction, ) -> Result<(), ProgramError> { msg!("Processing Bitcoin transaction"); // Verify Bitcoin transaction verify_bitcoin_transaction(bitcoin_tx)?; // Create state transition let state_transition = create_state_transition(counter_account, bitcoin_tx)?; // Add to transaction add_state_transition(state_transition)?; Ok(()) } fn verify_bitcoin_transaction(tx: &Transaction) -> Result<(), ProgramError> { // Implement Bitcoin transaction verification // Check signatures, inputs, outputs, etc. Ok(()) } fn create_state_transition( counter_account: &AccountInfo, bitcoin_tx: &Transaction, ) -> Result { // Create a Bitcoin transaction that reflects the state change let mut tx = Transaction { version: Version::TWO, lock_time: LockTime::ZERO, input: vec![], output: vec![], }; // Add inputs and outputs based on the counter state // This is a simplified example Ok(TransactionToSign::new(tx)) } ### [9.2 Error Handling and Logging](https://book.arch.network/docs/development/writing-your-first-program#92-error-handling-and-logging) Enhance error handling: use arch_program::msg; /// Enhanced error handling with detailed logging fn process_instruction_with_logging( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { msg!("=== Counter Program Execution ==="); msg!("Program ID: {}", program_id); msg!("Accounts: {}", accounts.len()); msg!("Instruction data length: {}", instruction_data.len()); match process_instruction(program_id, accounts, instruction_data) { Ok(()) => { msg!("Instruction processed successfully"); Ok(()) } Err(e) => { msg!("Instruction failed with error: {:?}", e); Err(e) } } } [Step 10: Security Best Practices](https://book.arch.network/docs/development/writing-your-first-program#step-10-security-best-practices) ------------------------------------------------------------------------------------------------------------------------------------------ ### [10.1 Input Validation](https://book.arch.network/docs/development/writing-your-first-program#101-input-validation) /// Validate instruction inputs fn validate_instruction(instruction: &CounterInstruction) -> Result<(), ProgramError> { match instruction { CounterInstruction::Initialize { initial_value } => { if *initial_value < 0 { return Err(CounterError::InvalidInstruction.into()); } } CounterInstruction::Increment { amount } => { if *amount <= 0 { return Err(CounterError::InvalidInstruction.into()); } } CounterInstruction::Decrement { amount } => { if *amount <= 0 { return Err(CounterError::InvalidInstruction.into()); } } _ => {} // Other instructions don't need validation } Ok(()) } ### [10.2 Access Control](https://book.arch.network/docs/development/writing-your-first-program#102-access-control) /// Enhanced access control fn verify_access_control( counter: &CounterAccount, owner_account: &AccountInfo, instruction: &CounterInstruction, ) -> Result<(), ProgramError> { // Check ownership if counter.owner != *owner_account.key { return Err(CounterError::Unauthorized.into()); } // Check if counter is active for state-changing operations match instruction { CounterInstruction::Increment { .. } | CounterInstruction::Decrement { .. } | CounterInstruction::Reset | CounterInstruction::Deactivate => { if !counter.is_active { return Err(CounterError::CounterInactive.into()); } } _ => {} // Read-only operations don't need active check } Ok(()) } [Next Steps](https://book.arch.network/docs/development/writing-your-first-program#next-steps) ----------------------------------------------------------------------------------------------- Congratulations! You've successfully created your first Arch program. Here's what you can do next: [### Explore More Examples\ \ Learn how to create fungible tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### Build an Oracle Program\ \ Create a price oracle for external data](https://book.arch.network/docs/development/how-to-write-oracle-program) [### Advanced Testing\ \ Learn comprehensive testing strategies](https://book.arch.network/docs/development/writing-your-first-program) [### Program Architecture\ \ Deep dive into Arch program concepts](https://book.arch.network/docs/development/writing-your-first-program) [Key Takeaways](https://book.arch.network/docs/development/writing-your-first-program#key-takeaways) ----------------------------------------------------------------------------------------------------- 1. **State Management**: Arch programs store state in accounts using Borsh serialization 2. **Instruction Processing**: Programs handle different instruction types through enums 3. **Security**: Always verify ownership and validate inputs 4. **Bitcoin Integration**: Programs can interact with Bitcoin transactions 5. **Testing**: Comprehensive testing is essential for production programs 6. **Error Handling**: Proper error handling improves user experience and security [Resources](https://book.arch.network/docs/development/writing-your-first-program#resources) --------------------------------------------------------------------------------------------- * [Arch Program Library](https://book.arch.network/docs/APL/introduction) - Pre-built programs and utilities * [SDK Documentation](https://book.arch.network/docs/tools-apis/sdk) - Client libraries and tools * [API Reference](https://book.arch.network/docs/tools-apis/api-reference) - Complete API documentation * [Community Discord](https://discord.gg/archnetwork) - Get help and share your projects [How to Write an Oracle Program\ \ Complete guide to building oracle programs that provide external data to other programs on Arch Network](https://book.arch.network/docs/development/how-to-write-oracle-program) [FAQ\ \ Frequently asked questions about Arch Network development](https://book.arch.network/docs/help-resources/faq) ### On this page [What You'll Build](https://book.arch.network/docs/development/writing-your-first-program#what-youll-build) [Prerequisites](https://book.arch.network/docs/development/writing-your-first-program#prerequisites) [Step 1: Project Setup](https://book.arch.network/docs/development/writing-your-first-program#step-1-project-setup) [1.1 Create Project Structure](https://book.arch.network/docs/development/writing-your-first-program#11-create-project-structure) [1.2 Configure Dependencies](https://book.arch.network/docs/development/writing-your-first-program#12-configure-dependencies) [1.3 Project Structure](https://book.arch.network/docs/development/writing-your-first-program#13-project-structure) [Step 2: Define Program Data Structures](https://book.arch.network/docs/development/writing-your-first-program#step-2-define-program-data-structures) [Step 3: Implement Program Logic](https://book.arch.network/docs/development/writing-your-first-program#step-3-implement-program-logic) [Step 4: Helper Functions](https://book.arch.network/docs/development/writing-your-first-program#step-4-helper-functions) [Step 5: Program Entry Point](https://book.arch.network/docs/development/writing-your-first-program#step-5-program-entry-point) [Step 6: Build and Deploy](https://book.arch.network/docs/development/writing-your-first-program#step-6-build-and-deploy) [6.1 Build the Program](https://book.arch.network/docs/development/writing-your-first-program#61-build-the-program) [6.2 Deploy to Local Network](https://book.arch.network/docs/development/writing-your-first-program#62-deploy-to-local-network) [Step 7: Create a Client](https://book.arch.network/docs/development/writing-your-first-program#step-7-create-a-client) [Step 8: Testing](https://book.arch.network/docs/development/writing-your-first-program#step-8-testing) [Step 9: Advanced Features](https://book.arch.network/docs/development/writing-your-first-program#step-9-advanced-features) [9.1 Bitcoin Integration](https://book.arch.network/docs/development/writing-your-first-program#91-bitcoin-integration) [9.2 Error Handling and Logging](https://book.arch.network/docs/development/writing-your-first-program#92-error-handling-and-logging) [Step 10: Security Best Practices](https://book.arch.network/docs/development/writing-your-first-program#step-10-security-best-practices) [10.1 Input Validation](https://book.arch.network/docs/development/writing-your-first-program#101-input-validation) [10.2 Access Control](https://book.arch.network/docs/development/writing-your-first-program#102-access-control) [Next Steps](https://book.arch.network/docs/development/writing-your-first-program#next-steps) [Key Takeaways](https://book.arch.network/docs/development/writing-your-first-program#key-takeaways) [Resources](https://book.arch.network/docs/development/writing-your-first-program#resources) --- # Syscalls Program Syscalls ======== A syscall is a function that can be used to obtain information from the underlying virtual machine. // Used for cross-program invocation (CPI) // Invokes a cross-program call define_syscall!(fn sol_invoke_signed_rust(instruction_addr: *const u8, account_infos_addr: *const u8, account_infos_len: u64) -> u64); // Sets the data to be returned for the cross-program invocation define_syscall!(fn sol_set_return_data(data: *const u8, length: u64)); // Returns the cross-program invocation data define_syscall!(fn sol_get_return_data(data: *mut u8, length: u64, program_id: *mut Pubkey) -> u64); // Arch // Validates and sets up transaction for being signed define_syscall!(fn arch_set_transaction_to_sign(transaction_to_sign: *const TransactionToSign)); // Retrieves raw Bitcoin transaction from RPC and copies into memory buffer define_syscall!(fn arch_get_bitcoin_tx(data: *mut u8, length: u64, txid: &[u8; 32]) -> u64); // Retrieves the multi-sig public key and copies into memory buffer define_syscall!(fn arch_get_network_xonly_pubkey(data: *mut u8) -> u64); // Validates ownership of a Bitcoin UTXO against a public key define_syscall!(fn arch_validate_utxo_ownership(utxo: *const UtxoMeta, owner: *const Pubkey) -> u64); // Generates a Bitcoin script public key and copies into memory buffer define_syscall!(fn arch_get_account_script_pubkey(script: *mut u8, pubkey: *const Pubkey) -> u64); // Retrieves the latest Bitcoin block height define_syscall!(fn arch_get_bitcoin_block_height() -> u64); // logs // Prints the hexidecimal representation of a string slice to stdout define_syscall!(fn sol_log_(message: *const u8, len: u64)); // Prints 64-bit values represented as hexadecimal to stdout define_syscall!(fn sol_log_64_(arg1: u64, arg2: u64, arg3: u64, arg4: u64, arg5: u64)); // Prints the hexidecimal representation of a public key to stdout define_syscall!(fn sol_log_pubkey(pubkey_addr: *const u8)); // Prints the base64 representation of a data array to stdout define_syscall!(fn sol_log_data(data: *const u8, data_len: u64)); [syscalls/definition.rs](https://github.com/Arch-Network/arch-examples/blob/main/program/src/syscalls/definitions.rs) [Program\ \ Previous Page](https://book.arch.network/docs/program/program) [πŸš€ Quick Start Guide\ \ Get your first program running on Arch Network in under 15 minutes](https://book.arch.network/docs/quick-start/quick-start) --- # Creating APL Tokens on Arch Network Development Creating APL Tokens on Arch Network =================================== Complete guide to creating and managing fungible tokens using the APL Token Program This guide shows you how to create and manage fungible tokens on Arch Network using the built-in **APL (Arch Program Library) Token Program**. APL tokens are based on Solana's SPL token standard and provide a robust foundation for creating and managing tokens on Arch Network. [What You'll Learn](https://book.arch.network/docs/development/how-to-create-a-fungible-token#what-youll-learn) ---------------------------------------------------------------------------------------------------------------- By the end of this guide, you'll understand how to: * **Create token mints** using the Arch CLI * **Initialize token accounts** for holding tokens * **Mint tokens** to accounts * **Transfer tokens** between accounts * **Approve delegations** for spending tokens * **Burn tokens** and manage token lifecycle * **Use advanced features** like multisig, freezing, and batch operations [Overview](https://book.arch.network/docs/development/how-to-create-a-fungible-token#overview) ----------------------------------------------------------------------------------------------- :::note All arch-cli addresses, public keys, transaction IDs, and block hashes are base58 (32 bytes for IDs/pubkeys). ::: The APL Token Program is Arch Network's native token standard, providing: * **SPL Token Compatibility**: Based on Solana's proven token standard * **Bitcoin Integration**: All operations are recorded on Bitcoin * **Comprehensive Features**: Minting, transferring, burning, delegation, freezing * **Multisig Support**: Multiple signature authorities for enhanced security * **CLI Integration**: Full command-line interface for token management [Prerequisites](https://book.arch.network/docs/development/how-to-create-a-fungible-token#prerequisites) --------------------------------------------------------------------------------------------------------- Before starting, ensure you have: * **Rust 1.84.1+** and Cargo installed ([Install Rust](https://rustup.rs/) ) * **Arch Network CLI** - [Download Latest](https://github.com/Arch-Network/arch-network/releases/latest) * **Docker** - Required for local development * **Running development environment** (see [Quick Start Guide](https://book.arch.network/docs/quick-start/quick-start) ) [APL Token Program ID](https://book.arch.network/docs/development/how-to-create-a-fungible-token#apl-token-program-id) ----------------------------------------------------------------------------------------------------------------------- The APL Token Program has a fixed program ID: AplToken111111111111111111111111 [Quick Start: Create Your First Token](https://book.arch.network/docs/development/how-to-create-a-fungible-token#quick-start-create-your-first-token) ------------------------------------------------------------------------------------------------------------------------------------------------------ ### [Step 1: Start Local Environment](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-1-start-local-environment) # Start local development environment arch-cli orchestrate start # Verify services are running arch-cli orchestrate validator-status arch-cli get-block-height ### [Step 2: Create Configuration Profile](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-2-create-configuration-profile) # Create a profile for local development arch-cli config create-profile local \ --bitcoin-node-endpoint http://127.0.0.1:18443 \ --bitcoin-node-username bitcoin \ --bitcoin-node-password bitcoinpass \ --bitcoin-network regtest \ --arch-node-url http://localhost:9002 \ --titan-url http://127.0.0.1:3030 # Set as default profile arch-cli config set-default-profile local ### [Step 3: Generate Demo Keys](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-3-generate-demo-keys) # Create directory for demo keys mkdir -p ~/DEMO_KEYS # Generate keys for different roles openssl rand -out ~/DEMO_KEYS/payer.key 32 openssl rand -out ~/DEMO_KEYS/mint_authority.key 32 openssl rand -out ~/DEMO_KEYS/mint.key 32 # Fund the payer account arch-cli account airdrop --keypair-path ~/DEMO_KEYS/payer.key ### [Step 4: Create Token Mint](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-4-create-token-mint) # Create a new token mint with 6 decimals (SPL-style) # Provide the mint authority and payer; optionally provide a mint keypair arch-cli token create-mint \ --decimals 6 \ --mint-authority ~/DEMO_KEYS/mint_authority.key \ --mint-keypair-path ~/DEMO_KEYS/mint.key \ --keypair-path ~/DEMO_KEYS/payer.key # Save the mint address (disable colors to parse reliably) export MINT=$(NO_COLOR=1 arch-cli token show-mint ~/DEMO_KEYS/mint.key | awk -F': ' '/^Address:/{print $2}') echo "Mint address: $MINT" ### [Step 5: Create Token Account](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-5-create-token-account) # Generate a keypair for the token account owner openssl rand -out ~/DEMO_KEYS/token_account_owner.key 32 # Create a token account for the owner arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/token_account_owner.key \ --keypair-path ~/DEMO_KEYS/payer.key # Save the token account address from the command output export TOKEN_ACCOUNT=$(NO_COLOR=1 arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/token_account_owner.key \ --keypair-path ~/DEMO_KEYS/payer.key \ | awk -F': ' '/^Account Address:/{print $2; exit}') echo "Token account: $TOKEN_ACCOUNT" ### [Step 6: Mint Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-6-mint-tokens) # Mint 1,000 tokens to the token account (with 6 decimals) arch-cli token mint "$MINT" 1000000000 \ --account-address "$TOKEN_ACCOUNT" \ --authority ~/DEMO_KEYS/mint_authority.key \ --auto-create-ata \ --keypair-path ~/DEMO_KEYS/payer.key # Check the token account balance arch-cli token balance "$TOKEN_ACCOUNT" [Advanced Token Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#advanced-token-operations) --------------------------------------------------------------------------------------------------------------------------------- ### [Transfer Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#transfer-tokens) # Create a second token account for transfers openssl rand -out ~/DEMO_KEYS/recipient.key 32 arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/recipient.key \ --keypair-path ~/DEMO_KEYS/payer.key export RECIPIENT_ACCOUNT=$(NO_COLOR=1 arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/recipient.key \ --keypair-path ~/DEMO_KEYS/payer.key \ | awk -F': ' '/^Account Address:/{print $2; exit}') # Transfer 100 tokens (100000000 units with 6 decimals) arch-cli token transfer "$TOKEN_ACCOUNT" "$RECIPIENT_ACCOUNT" 100000000 \ --owner ~/DEMO_KEYS/token_account_owner.key ### [Approve Delegation](https://book.arch.network/docs/development/how-to-create-a-fungible-token#approve-delegation) # Generate a delegate keypair openssl rand -out ~/DEMO_KEYS/delegate.key 32 # Approve the delegate to spend 50 tokens (use delegate's base58 public key) export DELEGATE_PUBKEY= arch-cli token approve "$TOKEN_ACCOUNT" "$DELEGATE_PUBKEY" 50000000 \ --owner ~/DEMO_KEYS/token_account_owner.key # Check the balance arch-cli token balance "$TOKEN_ACCOUNT" ### [Transfer from Delegate](https://book.arch.network/docs/development/how-to-create-a-fungible-token#transfer-from-delegate) # Transfer tokens using the delegate as the signer arch-cli token transfer "$TOKEN_ACCOUNT" "$RECIPIENT_ACCOUNT" 25000000 \ --owner ~/DEMO_KEYS/delegate.key ### [Burn Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#burn-tokens) # Burn 10 tokens from the token account arch-cli token burn \ --account $TOKEN_ACCOUNT \ --amount 10000000 \ --owner ~/DEMO_KEYS/token_account_owner.key \ --keypair-path ~/DEMO_KEYS/payer.key [Token Account Management](https://book.arch.network/docs/development/how-to-create-a-fungible-token#token-account-management) ------------------------------------------------------------------------------------------------------------------------------- ### [Freeze and Thaw Accounts](https://book.arch.network/docs/development/how-to-create-a-fungible-token#freeze-and-thaw-accounts) # Freeze the token account (prevents transfers) arch-cli token freeze-account "$TOKEN_ACCOUNT" \ --authority ~/DEMO_KEYS/mint_authority.key # Thaw the account (re-enable transfers) arch-cli token thaw-account "$TOKEN_ACCOUNT" \ --authority ~/DEMO_KEYS/freeze_authority.key ### [Close Token Account](https://book.arch.network/docs/development/how-to-create-a-fungible-token#close-token-account) # Close the token account (reclaims rent) arch-cli token close-account "$TOKEN_ACCOUNT" \ --owner ~/DEMO_KEYS/token_account_owner.key [Multisig Token Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#multisig-token-operations) --------------------------------------------------------------------------------------------------------------------------------- ### [Create Multisig Mint Authority](https://book.arch.network/docs/development/how-to-create-a-fungible-token#create-multisig-mint-authority) # Generate multiple authority keypairs openssl rand -out ~/DEMO_KEYS/authority1.key 32 openssl rand -out ~/DEMO_KEYS/authority2.key 32 openssl rand -out ~/DEMO_KEYS/authority3.key 32 # Create a multisig (2-of-3) export MULTISIG=$(NO_COLOR=1 arch-cli token create-multisig 2 \ --signers ~/DEMO_KEYS/authority1.key,~/DEMO_KEYS/authority2.key,~/DEMO_KEYS/authority3.key \ --keypair-path ~/DEMO_KEYS/payer.key | awk -F': ' '/^Multisig Address:/{print $2; exit}') ### [Mint with Multisig](https://book.arch.network/docs/development/how-to-create-a-fungible-token#mint-with-multisig) # Set the mint's authority to the multisig address arch-cli token set-authority "$MINT" \ --authority-type mint \ --new-authority "$MULTISIG" \ --current-authority ~/DEMO_KEYS/mint_authority.key # Create a token account for the recipient arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/token_account_owner.key \ --keypair-path ~/DEMO_KEYS/payer.key export MULTISIG_ACCOUNT=$(NO_COLOR=1 arch-cli token create-account \ --mint "$MINT" \ --owner ~/DEMO_KEYS/token_account_owner.key \ --keypair-path ~/DEMO_KEYS/payer.key \ | awk -F': ' '/^Account Address:/{print $2; exit}') # Mint using multisig (provide multisig address and two signer keypairs) arch-cli token mint "$MINT" 1000000000 \ --account-address "$MULTISIG_ACCOUNT" \ --authority ~/DEMO_KEYS/authority1.key \ --multisig "$MULTISIG" \ --signers ~/DEMO_KEYS/authority1.key,~/DEMO_KEYS/authority2.key \ --keypair-path ~/DEMO_KEYS/payer.key [Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#token-metadata) ----------------------------------------------------------------------------------------------------------- ### [Set Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#set-token-metadata) # Set metadata for your token arch-cli token set-metadata \ --mint $MINT \ --name "My Awesome Token" \ --symbol "MAT" \ --description "A demonstration token for Arch Network" \ --image "https://example.com/token-image.png" \ --mint-authority ~/DEMO_KEYS/mint_authority.key \ --keypair-path ~/DEMO_KEYS/payer.key ### [View Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#view-token-metadata) # View the token metadata arch-cli token show-metadata --mint $MINT [Batch Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#batch-operations) --------------------------------------------------------------------------------------------------------------- ### [Batch Transfer](https://book.arch.network/docs/development/how-to-create-a-fungible-token#batch-transfer) # Create multiple recipient accounts for i in {1..3}; do openssl rand -out ~/DEMO_KEYS/recipient$i.key 32 arch-cli token create-account \ --mint $MINT \ --owner ~/DEMO_KEYS/recipient$i.key \ --keypair-path ~/DEMO_KEYS/payer.key done # Batch transfer using a JSON file # Example transfers.json: [{"source_account":"$TOKEN_ACCOUNT","destination_account":"","amount":100000000,"owner_keypair_path":"~/DEMO_KEYS/token_account_owner.key"}] arch-cli token batch-transfer ./transfers.json \ --keypair-path ~/DEMO_KEYS/payer.key [Error Handling and Troubleshooting](https://book.arch.network/docs/development/how-to-create-a-fungible-token#error-handling-and-troubleshooting) --------------------------------------------------------------------------------------------------------------------------------------------------- ### [Common Issues](https://book.arch.network/docs/development/how-to-create-a-fungible-token#common-issues) **Insufficient Balance:** # Check account balance before operations arch-cli token show-account --mint $MINT --owner ~/DEMO_KEYS/token_account_owner.key **Invalid Authority:** # Verify you're using the correct authority keypair arch-cli token show-mint "$MINT" # If you see an authority mismatch when minting: # 1) Verify the mint's current Mint Authority matches your keypair's pubkey NO_COLOR=1 arch-cli token show-mint "$MINT" | awk -F': ' '/^Mint Authority:/{print $2}' # 2) If wrong, either switch to the correct keypair or update the authority: arch-cli token set-authority "$MINT" \ --authority-type mint \ --new-authority \ --current-authority ~/DEMO_KEYS/mint_authority.key ### [Verify Authority Before Minting](https://book.arch.network/docs/development/how-to-create-a-fungible-token#verify-authority-before-minting) # Derive pubkeys without funding (amount 0 prints the public key) OWNER_PUB=$(NO_COLOR=1 arch-cli account airdrop --keypair-path ~/DEMO_KEYS/token_account_owner.key --amount 0 2>/dev/null | awk -F': ' '/^ Public key:/{print $2}') MINT_AUTH_PUB=$(NO_COLOR=1 arch-cli account airdrop --keypair-path ~/DEMO_KEYS/mint_authority.key --amount 0 2>/dev/null | awk -F': ' '/^ Public key:/{print $2}') CHAIN_MINT_AUTH=$(NO_COLOR=1 arch-cli token show-mint "$MINT" | awk -F': ' '/^Mint Authority:/{print $2}') echo "Owner: $OWNER_PUB" echo "MintAuthKey: $MINT_AUTH_PUB" echo "ChainMintAuth: $CHAIN_MINT_AUTH" # Must match before minting test "$MINT_AUTH_PUB" = "$CHAIN_MINT_AUTH" || echo "Mint authority mismatch: rotate or recreate mint." ### [Reset Demo Keys (Dev Only)](https://book.arch.network/docs/development/how-to-create-a-fungible-token#reset-demo-keys-dev-only) # Destroys local keys; only do this for demo/dev mints rm -rf ~/DEMO_KEYS mkdir -p ~/DEMO_KEYS # Recreate stable keys ONCE (don’t regenerate after mint creation) openssl rand -out ~/DEMO_KEYS/payer.key 32 openssl rand -out ~/DEMO_KEYS/mint_authority.key 32 openssl rand -out ~/DEMO_KEYS/mint.key 32 openssl rand -out ~/DEMO_KEYS/token_account_owner.key 32 # Fund payer arch-cli account airdrop --keypair-path ~/DEMO_KEYS/payer.key # Recreate mint (uses the mint_authority you just generated) arch-cli token create-mint \ --decimals 6 \ --mint-authority ~/DEMO_KEYS/mint_authority.key \ --mint-keypair-path ~/DEMO_KEYS/mint.key \ --keypair-path ~/DEMO_KEYS/payer.key export MINT=$(NO_COLOR=1 arch-cli token show-mint ~/DEMO_KEYS/mint.key | awk -F': ' '/^Address:/{print $2}') ### [Key Roles](https://book.arch.network/docs/development/how-to-create-a-fungible-token#key-roles) * Payer (`--keypair-path`): pays fees; required when creating ATAs * Mint authority (`--authority`): must equal on-chain Mint Authority * Owner (`--account-address`): owner’s base58 pubkey; CLI derives/creates the ATA **Account Not Found:** # Ensure the token account exists arch-cli token show-account --mint $MINT --owner ~/DEMO_KEYS/token_account_owner.key ### [Debug Commands](https://book.arch.network/docs/development/how-to-create-a-fungible-token#debug-commands) # Show detailed token information arch-cli token show-mint "$MINT" # Show account details arch-cli token show-account "$TOKEN_ACCOUNT" # Check transaction status arch-cli tx confirm # View program logs arch-cli tx log-program-messages [Best Practices](https://book.arch.network/docs/development/how-to-create-a-fungible-token#best-practices) ----------------------------------------------------------------------------------------------------------- ### [Security](https://book.arch.network/docs/development/how-to-create-a-fungible-token#security) 1. **Secure Key Management**: Store private keys securely and never share them 2. **Use Multisig**: Implement multisig for important operations 3. **Regular Audits**: Regularly audit token operations and balances 4. **Access Control**: Implement proper access controls for mint authorities ### [Performance](https://book.arch.network/docs/development/how-to-create-a-fungible-token#performance) 1. **Batch Operations**: Use batch operations for multiple transfers 2. **Account Management**: Close unused accounts to reclaim rent 3. **Efficient Decimals**: Choose appropriate decimal places for your use case 4. **Monitor Gas**: Monitor transaction costs and optimize accordingly ### [Development](https://book.arch.network/docs/development/how-to-create-a-fungible-token#development) 1. **Test Thoroughly**: Test all operations in development before production 2. **Error Handling**: Implement proper error handling in your applications 3. **Documentation**: Document your token's purpose and operations 4. **Community**: Follow community best practices and standards [Integration Examples](https://book.arch.network/docs/development/how-to-create-a-fungible-token#integration-examples) ----------------------------------------------------------------------------------------------------------------------- ### [TypeScript Integration](https://book.arch.network/docs/development/how-to-create-a-fungible-token#typescript-integration) import { ArchNetworkClient } from '@arch-network/sdk'; const client = new ArchNetworkClient('http://localhost:9002'); // Create a token mint const mint = await client.createTokenMint({ decimals: 6, mintAuthority: mintAuthorityKeypair, payer: payerKeypair }); // Create a token account const tokenAccount = await client.createTokenAccount({ mint: mint.publicKey, owner: ownerKeypair.publicKey, payer: payerKeypair }); // Mint tokens await client.mintTo({ mint: mint.publicKey, destination: tokenAccount, amount: 1000000000, mintAuthority: mintAuthorityKeypair }); ### [Rust Integration](https://book.arch.network/docs/development/how-to-create-a-fungible-token#rust-integration) use arch_network_sdk::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { let client = ArchNetworkClient::new("http://localhost:9002").await?; // Create token mint let mint = client.create_token_mint( CreateTokenMintParams { decimals: 6, mint_authority: &mint_authority_keypair, payer: &payer_keypair, } ).await?; // Create token account let token_account = client.create_token_account( CreateTokenAccountParams { mint: mint.pubkey(), owner: owner_keypair.pubkey(), payer: &payer_keypair, } ).await?; // Mint tokens client.mint_to( MintToParams { mint: mint.pubkey(), destination: token_account, amount: 1000000000, mint_authority: &mint_authority_keypair, } ).await?; Ok(()) } [Next Steps](https://book.arch.network/docs/development/how-to-create-a-fungible-token#next-steps) --------------------------------------------------------------------------------------------------- [### Oracle Program Guide\ \ Learn to build price oracles](https://book.arch.network/docs/development/how-to-write-oracle-program) [### Runes Swap Guide\ \ Build a token swap protocol](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap) [### Lending Protocol\ \ Create a lending protocol](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol) [### APL Documentation\ \ Deep dive into the APL Token Program](https://book.arch.network/docs/APL/token-program) [Resources](https://book.arch.network/docs/development/how-to-create-a-fungible-token#resources) ------------------------------------------------------------------------------------------------- [### APL Token Program\ \ Complete APL Token Program documentation](https://book.arch.network/docs/APL/token-program) [### SDK Reference\ \ Client SDK documentation](https://book.arch.network/docs/tools-apis/sdk) [### CLI Reference\ \ Complete CLI command reference](https://book.arch.network/docs/tools-apis/arch-cli-reference) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [Building Your First Bitcoin Runes Swap Application\ \ Complete guide to building a decentralized Runes token swap application on Arch Network](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap) [How to Write an Oracle Program\ \ Complete guide to building oracle programs that provide external data to other programs on Arch Network](https://book.arch.network/docs/development/how-to-write-oracle-program) ### On this page [What You'll Learn](https://book.arch.network/docs/development/how-to-create-a-fungible-token#what-youll-learn) [Overview](https://book.arch.network/docs/development/how-to-create-a-fungible-token#overview) [Prerequisites](https://book.arch.network/docs/development/how-to-create-a-fungible-token#prerequisites) [APL Token Program ID](https://book.arch.network/docs/development/how-to-create-a-fungible-token#apl-token-program-id) [Quick Start: Create Your First Token](https://book.arch.network/docs/development/how-to-create-a-fungible-token#quick-start-create-your-first-token) [Step 1: Start Local Environment](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-1-start-local-environment) [Step 2: Create Configuration Profile](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-2-create-configuration-profile) [Step 3: Generate Demo Keys](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-3-generate-demo-keys) [Step 4: Create Token Mint](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-4-create-token-mint) [Step 5: Create Token Account](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-5-create-token-account) [Step 6: Mint Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#step-6-mint-tokens) [Advanced Token Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#advanced-token-operations) [Transfer Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#transfer-tokens) [Approve Delegation](https://book.arch.network/docs/development/how-to-create-a-fungible-token#approve-delegation) [Transfer from Delegate](https://book.arch.network/docs/development/how-to-create-a-fungible-token#transfer-from-delegate) [Burn Tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token#burn-tokens) [Token Account Management](https://book.arch.network/docs/development/how-to-create-a-fungible-token#token-account-management) [Freeze and Thaw Accounts](https://book.arch.network/docs/development/how-to-create-a-fungible-token#freeze-and-thaw-accounts) [Close Token Account](https://book.arch.network/docs/development/how-to-create-a-fungible-token#close-token-account) [Multisig Token Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#multisig-token-operations) [Create Multisig Mint Authority](https://book.arch.network/docs/development/how-to-create-a-fungible-token#create-multisig-mint-authority) [Mint with Multisig](https://book.arch.network/docs/development/how-to-create-a-fungible-token#mint-with-multisig) [Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#token-metadata) [Set Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#set-token-metadata) [View Token Metadata](https://book.arch.network/docs/development/how-to-create-a-fungible-token#view-token-metadata) [Batch Operations](https://book.arch.network/docs/development/how-to-create-a-fungible-token#batch-operations) [Batch Transfer](https://book.arch.network/docs/development/how-to-create-a-fungible-token#batch-transfer) [Error Handling and Troubleshooting](https://book.arch.network/docs/development/how-to-create-a-fungible-token#error-handling-and-troubleshooting) [Common Issues](https://book.arch.network/docs/development/how-to-create-a-fungible-token#common-issues) [Verify Authority Before Minting](https://book.arch.network/docs/development/how-to-create-a-fungible-token#verify-authority-before-minting) [Reset Demo Keys (Dev Only)](https://book.arch.network/docs/development/how-to-create-a-fungible-token#reset-demo-keys-dev-only) [Key Roles](https://book.arch.network/docs/development/how-to-create-a-fungible-token#key-roles) [Debug Commands](https://book.arch.network/docs/development/how-to-create-a-fungible-token#debug-commands) [Best Practices](https://book.arch.network/docs/development/how-to-create-a-fungible-token#best-practices) [Security](https://book.arch.network/docs/development/how-to-create-a-fungible-token#security) [Performance](https://book.arch.network/docs/development/how-to-create-a-fungible-token#performance) [Development](https://book.arch.network/docs/development/how-to-create-a-fungible-token#development) [Integration Examples](https://book.arch.network/docs/development/how-to-create-a-fungible-token#integration-examples) [TypeScript Integration](https://book.arch.network/docs/development/how-to-create-a-fungible-token#typescript-integration) [Rust Integration](https://book.arch.network/docs/development/how-to-create-a-fungible-token#rust-integration) [Next Steps](https://book.arch.network/docs/development/how-to-create-a-fungible-token#next-steps) [Resources](https://book.arch.network/docs/development/how-to-create-a-fungible-token#resources) --- # ROAST and FROST Consensus Core Concepts ROAST and FROST Consensus ========================= Arch's consensus mechanism combining ROAST and FROST for secure, efficient distributed consensus This section explores Arch's consensus mechanism, which combines ROAST (Robust Asynchronous Schnorr Threshold Signatures) and FROST (Flexible Round-Optimized Schnorr Threshold Signatures) to create a secure, efficient, and highly scalable approach to distributed consensus that's perfectly suited for Bitcoin-based smart contracts. [Implementation Status](https://book.arch.network/docs/core-concepts/consensus#implementation-status) ------------------------------------------------------------------------------------------------------ The consensus mechanism implementation has made significant progress, particularly in the core cryptographic components: 1. **Implemented Components** * Complete Distributed Key Generation (DKG) protocol using FROST-secp256k1 * Two-round DKG process with package handling * Network message protocol for DKG coordination * State management and status tracking * Integration with network layer * Error handling and recovery mechanisms 2. **In Progress** * Additional ROAST protocol components * Advanced state management features * Performance optimizations * Extended monitoring and telemetry The subsequent sections describe both the implemented features and the complete protocol design. [Core Implementation Details](https://book.arch.network/docs/core-concepts/consensus#core-implementation-details) ------------------------------------------------------------------------------------------------------------------ ### [Distributed Key Generation (DKG)](https://book.arch.network/docs/core-concepts/consensus#distributed-key-generation-dkg) // Core DKG message types for network coordination pub enum DKGMessage { StartDKG { message: String }, Round1Package { package: round1::Package }, Round2Package { package: round2::Package }, DKGStatus(DKGStatusMessage), } // DKG state management pub enum DKGStatus { Pending(String), Ongoing(String), Failed(String, String), Finished(String), NetworkCompleted(String), } The DKG implementation provides: * Two-round key generation protocol * Secure package exchange between validators * State tracking and synchronization * Failure recovery and error handling [Distributed Key Generation (DKG) Deep Dive](https://book.arch.network/docs/core-concepts/consensus#distributed-key-generation-dkg-deep-dive) ---------------------------------------------------------------------------------------------------------------------------------------------- ### [What is DKG?](https://book.arch.network/docs/core-concepts/consensus#what-is-dkg) Distributed Key Generation (DKG) is the cryptographic process that allows a group of validators to collectively generate a master key pair without any single validator knowing the complete private key. This is the foundation of Arch's threshold signature scheme. ### [Why DKG is Critical](https://book.arch.network/docs/core-concepts/consensus#why-dkg-is-critical) In Arch's consensus model: * **No single point of failure**: No validator can sign alone * **Threshold security**: Only a subset of validators (e.g., 2-of-3) need to cooperate * **Distributed trust**: The network's security doesn't depend on any single party * **Bitcoin compatibility**: Uses the same secp256k1 curve as Bitcoin ### [The DKG Process Flow](https://book.arch.network/docs/core-concepts/consensus#the-dkg-process-flow) #### [Phase 1: Network Initialization](https://book.arch.network/docs/core-concepts/consensus#phase-1-network-initialization) 1. **Validator Startup**: Each validator starts in `WaitingForDkg` state 2. **Peer Discovery**: Validators connect to each other and the bootnode 3. **Whitelist Verification**: All validators in the whitelist must be online 4. **Leader Initiation**: The designated leader triggers DKG when all peers are ready #### [Phase 2: Round 1 - Commitment Generation](https://book.arch.network/docs/core-concepts/consensus#phase-2-round-1---commitment-generation) Each validator: * Generates a random secret share * Creates polynomial commitments * Broadcasts Round1 packages to all peers * Waits for Round1 packages from all other validators #### [Phase 3: Round 2 - Key Generation](https://book.arch.network/docs/core-concepts/consensus#phase-3-round-2---key-generation) Each validator: * Receives Round1 packages from all peers * Computes their contribution to the final key * Generates Round2 packages with signed shares * Exchanges Round2 packages with all peers #### [Phase 4: Finalization](https://book.arch.network/docs/core-concepts/consensus#phase-4-finalization) Each validator: * Combines all Round2 packages * Computes the final `PublicKeyPackage` * Saves the `pubkey_package.json` file * Transitions to `Ready` state ### [The `pubkey_package.json` File](https://book.arch.network/docs/core-concepts/consensus#the-pubkey_packagejson-file) #### [Location and Structure](https://book.arch.network/docs/core-concepts/consensus#location-and-structure) The `pubkey_package.json` file is automatically created in: {data_dir}/{network_mode}/pubkey_package.json For example: `./.arch_data/devnet/pubkey_package.json` #### [File Format](https://book.arch.network/docs/core-concepts/consensus#file-format) { "verifying_key": { "element": "02a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7" }, "verifying_shares": { "0000000000000000000000000000000000000000000000000000000000000001": { "element": "02b8d9aa7c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0" }, "0000000000000000000000000000000000000000000000000000000000000002": { "element": "03c9eabb8d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1" } } } #### [What Each Field Represents](https://book.arch.network/docs/core-concepts/consensus#what-each-field-represents) * **`verifying_key`**: The master public key for the entire validator set * **`verifying_shares`**: Individual public keys for each validator's share * **`element` fields**: secp256k1 curve points in compressed format ### [Key Security Properties](https://book.arch.network/docs/core-concepts/consensus#key-security-properties) #### [Threshold Signing](https://book.arch.network/docs/core-concepts/consensus#threshold-signing) * **2-of-3 example**: With 3 validators, only 2 need to cooperate to sign * **No single point of failure**: No validator can sign alone * **Flexible thresholds**: Can be configured for different security levels #### [Cryptographic Guarantees](https://book.arch.network/docs/core-concepts/consensus#cryptographic-guarantees) * **Information theoretic security**: Based on proven cryptographic principles * **Forward secrecy**: Compromised shares don't reveal past signatures * **Verifiable**: All participants can verify the correctness of the process [Block Production Process](https://book.arch.network/docs/core-concepts/consensus#block-production-process) ------------------------------------------------------------------------------------------------------------ ### [1\. Leader Selection](https://book.arch.network/docs/core-concepts/consensus#1-leader-selection) The block production process begins with leader selection: * Each epoch (fixed time period) has a predetermined leader schedule * Leaders are selected based on their stake weight * The schedule is deterministic and known to all validators * Multiple backup leaders are selected for fault tolerance ### [2\. Transaction Collection and Verification](https://book.arch.network/docs/core-concepts/consensus#2-transaction-collection-and-verification) When a validator becomes the leader: 1. Collects pending transactions from the mempool 2. Verifies transaction signatures and validity 3. Orders transactions based on priority and fees 4. Prepares them for inclusion in the next block ### [3\. Block Formation](https://book.arch.network/docs/core-concepts/consensus#3-block-formation) The block structure includes: * Previous block reference * Timestamp * Transaction merkle root * UTXO state updates * Leader's signature [Consensus Process](https://book.arch.network/docs/core-concepts/consensus#consensus-process) ---------------------------------------------------------------------------------------------- ### [1\. Block Validation](https://book.arch.network/docs/core-concepts/consensus#1-block-validation) When validators receive a new block: 1. Verify the block producer is the designated leader 2. Validate all transaction signatures 3. Execute transactions and verify UTXO states 4. Check for any consensus rule violations ### [2\. UTXO-Based State Management](https://book.arch.network/docs/core-concepts/consensus#2-utxo-based-state-management) Arch's unique approach to state management leverages Bitcoin's UTXO model while extending it for smart contract functionality: #### [UTXO State Tracking](https://book.arch.network/docs/core-concepts/consensus#utxo-state-tracking) pub struct UtxoState { pub meta: UtxoMeta, // UTXO identification pub status: UtxoStatus, // Current UTXO status pub owner: Pubkey, // UTXO owner pub created_at: i64, // Creation timestamp pub spent_at: Option, // Spend timestamp if spent } pub enum UtxoStatus { Pending, // Waiting for confirmations Active, // Confirmed and spendable Spent, // UTXO has been consumed Invalid, // UTXO was invalidated (e.g., by reorg) } #### [State Transition Process](https://book.arch.network/docs/core-concepts/consensus#state-transition-process) 1. **UTXO Validation** * Verify UTXO existence on Bitcoin * Check confirmation requirements (typically 6+) * Validate ownership and spending conditions * Prevent double-spending attempts 2. **State Updates** * Atomic account data modifications * Program state transitions * UTXO set updates * Cross-validator state consistency 3. **Bitcoin Integration** * State anchoring to Bitcoin transactions * Threshold signature aggregation * Transaction finality through Bitcoin confirmations * Reorg handling and state rollbacks ### [3\. FROST Signing Process](https://book.arch.network/docs/core-concepts/consensus#3-frost-signing-process) The FROST signing process involves: 1. Each validator generates their partial signature 2. Signatures are shared among the threshold group 3. Partial signatures are aggregated into a final signature 4. The aggregated signature is verified against the group public key ### [4\. ROAST Enhancement Layer](https://book.arch.network/docs/core-concepts/consensus#4-roast-enhancement-layer) ROAST transforms FROST into a production-ready consensus mechanism by adding several crucial enhancements: #### [Asynchronous Operation Guarantees](https://book.arch.network/docs/core-concepts/consensus#asynchronous-operation-guarantees) Unlike traditional consensus mechanisms that require strict synchronization: * Validators can participate in signing rounds without tight timing constraints * The protocol progresses even when some validators are temporarily delayed * Network partitions and varying message delivery times are handled gracefully * No assumptions about network synchrony are required for safety #### [Byzantine Fault Tolerance](https://book.arch.network/docs/core-concepts/consensus#byzantine-fault-tolerance) ROAST maintains safety and liveness even in the presence of malicious actors: * Tolerates up to f Byzantine validators where f < n/3 * Malicious behavior is detected and isolated * Signature shares from Byzantine validators can be identified and excluded * The protocol remains secure even if Byzantine validators: * Submit invalid signature shares * Attempt to sign conflicting blocks * Try to delay or prevent consensus * Collude with other malicious validators [Understanding FROST](https://book.arch.network/docs/core-concepts/consensus#understanding-frost) -------------------------------------------------------------------------------------------------- FROST is a threshold signature scheme that enables a group of participants to collectively generate Schnorr signatures. This foundational protocol is crucial for Arch's consensus mechanism because it provides a way to achieve distributed agreement while maintaining compatibility with Bitcoin's native signature scheme. ### [Key Components](https://book.arch.network/docs/core-concepts/consensus#key-components) * **Distributed Key Generation**: Validators collectively participate in a process that generates a shared public key while keeping individual private key shares separate and secure. * **Threshold Signatures**: The system requires a specific number of validators (t-of-n) to cooperate in order to produce valid signatures, balancing security with fault tolerance. * **Share Management**: Each validator maintains their own private key share, contributing to the system's security through distribution of trust. * **Signature Aggregation**: Multiple partial signatures are combined into a single Schnorr signature that's indistinguishable from a standard single-signer signature. ### [Benefits of FROST](https://book.arch.network/docs/core-concepts/consensus#benefits-of-frost) 1. **Enhanced Security** * No single validator can compromise the system * Distributed trust model eliminates single points of failure * Cryptographic guarantees of signature validity 2. **Bitcoin Compatibility** * Native integration with Bitcoin's Schnorr signature scheme * No additional on-chain overhead * Seamless interaction with Bitcoin's transaction validation 3. **Efficiency** * Constant-size signatures regardless of validator count * Optimized communication patterns * Reduced blockchain space usage [ROAST: Enhancing FROST for Production](https://book.arch.network/docs/core-concepts/consensus#roast-enhancing-frost-for-production) ------------------------------------------------------------------------------------------------------------------------------------- While FROST provides the cryptographic foundation, ROAST adds crucial properties needed for real-world deployment in adversarial environments. ROAST transforms FROST from a theoretical protocol into a production-ready consensus mechanism. ### [Key Enhancements](https://book.arch.network/docs/core-concepts/consensus#key-enhancements) 1. **Asynchronous Operation** * Validators can participate without strict timing requirements * Resilient to network delays and partitions * Maintains liveness in real-world conditions 2. **Robustness Against Attacks** * Continues operating even with malicious participants * Detects and handles various forms of validator misbehavior * Provides provable security guarantees 3. **Leader Selection** * Efficient and fair leader rotation mechanism * Prevents centralization of power * Maintains system progress even if leaders fail 4. **Liveness Guarantees** * Ensures forward progress under adverse conditions * Handles validator churn gracefully * Recovers automatically from temporary failures [Security Considerations](https://book.arch.network/docs/core-concepts/consensus#security-considerations) ---------------------------------------------------------------------------------------------------------- ### [Threat Model](https://book.arch.network/docs/core-concepts/consensus#threat-model) * **Byzantine Validators**: System remains secure with up to f Byzantine validators (where f < n/3) * **Network Adversaries**: Resilient against various network-level attacks * **Cryptographic Security**: Based on well-studied cryptographic assumptions ### [Security Properties](https://book.arch.network/docs/core-concepts/consensus#security-properties) 1. **Safety** * No conflicting transactions can be confirmed * Cryptographic guarantees of transaction finality * Protection against double-spending 2. **Liveness** * System continues to make progress * Recovers from temporary failures * Handles validator set changes 3. **Fault Tolerance** * Continues operating with partial validator failures * Graceful degradation under attack * Automatic recovery mechanisms [Further Reading](https://book.arch.network/docs/core-concepts/consensus#further-reading) ------------------------------------------------------------------------------------------ ### [Academic Papers and Research](https://book.arch.network/docs/core-concepts/consensus#academic-papers-and-research) #### [FROST (Flexible Round-Optimized Schnorr Threshold Signatures)](https://book.arch.network/docs/core-concepts/consensus#frost-flexible-round-optimized-schnorr-threshold-signatures) * [FROST: Flexible Round-Optimized Schnorr Threshold Signatures](https://eprint.iacr.org/2020/852.pdf) - The original FROST paper by Chelsea Komlo and Ian Goldberg * [Two-Round Threshold Schnorr Signatures with FROST](https://eprint.iacr.org/2021/1110.pdf) - An optimized two-round variant of FROST * [Implementing FROST](https://github.com/ZcashFoundation/frost) - Reference implementation by the Zcash Foundation #### [ROAST (Robust Asynchronous Schnorr Threshold Signatures)](https://book.arch.network/docs/core-concepts/consensus#roast-robust-asynchronous-schnorr-threshold-signatures) * [ROAST: Robust Asynchronous Schnorr Threshold Signatures](https://eprint.iacr.org/2022/550.pdf) - The foundational ROAST paper * [Practical Threshold Signatures for Bitcoin](https://medium.com/blockstream/implementing-threshold-signatures-for-bitcoin-8d3b63831325) - Implementation insights for Bitcoin-based threshold signatures #### [Threshold Cryptography and Consensus](https://book.arch.network/docs/core-concepts/consensus#threshold-cryptography-and-consensus) * [A Survey of Distributed Consensus Protocols for Blockchain Networks](https://arxiv.org/pdf/1904.04098.pdf) - Comprehensive overview of consensus mechanisms * [Threshold Signatures: The Future of Consensus?](https://eprint.iacr.org/2019/1157.pdf) - Analysis of threshold signatures in consensus protocols * [Schnorr Multi-Signatures and Applications](https://eprint.iacr.org/2018/068.pdf) - Foundational work on Schnorr multi-signatures ### [Technical Resources](https://book.arch.network/docs/core-concepts/consensus#technical-resources) #### [Implementation Guides](https://book.arch.network/docs/core-concepts/consensus#implementation-guides) * [BIP 340: Schnorr Signatures for secp256k1](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki) - Bitcoin Improvement Proposal for Schnorr signatures * [Implementing Threshold Signatures](https://tlu.tarilabs.com/cryptography/threshold-signatures) - Technical guide on threshold signature implementation * [Multi-Party Computation for Distributed Key Generation](https://github.com/ZcashFoundation/redjubjub) - Reference implementation of distributed key generation #### [Security Analysis](https://book.arch.network/docs/core-concepts/consensus#security-analysis) * [Security Analysis of Threshold Signature Schemes](https://eprint.iacr.org/2019/114.pdf) - Comprehensive security analysis * [Formal Verification of FROST](https://eprint.iacr.org/2021/1559.pdf) - Formal security proofs for FROST * [Byzantine Fault Tolerance in Distributed Systems](https://arxiv.org/pdf/1908.01738.pdf) - Analysis of BFT in consensus protocols ### [Community Resources](https://book.arch.network/docs/core-concepts/consensus#community-resources) * [FROST Working Group](https://frost.zfnd.org/) - Community working group on FROST implementation * [Bitcoin Dev Mailing List](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/) - Discussions on threshold signatures in Bitcoin [Conclusion](https://book.arch.network/docs/core-concepts/consensus#conclusion) -------------------------------------------------------------------------------- The combination of ROAST and FROST in Arch represents a significant advancement in Bitcoin-based smart contract platforms. This consensus mechanism enables sophisticated applications while maintaining the security and decentralization principles that make Bitcoin valuable. Through careful design and implementation, Arch has created a system that is not just theoretically sound but practically deployable and scalable for real-world applications. [Bitcoin Integration\ \ How Arch Network integrates with Bitcoin through UTXO management and RPC interfaces](https://book.arch.network/docs/core-concepts/bitcoin-integration) [How to Build a Bitcoin Lending Protocol\ \ Complete guide to building a decentralized lending protocol for Bitcoin-based assets on Arch Network](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol) ### On this page [Implementation Status](https://book.arch.network/docs/core-concepts/consensus#implementation-status) [Core Implementation Details](https://book.arch.network/docs/core-concepts/consensus#core-implementation-details) [Distributed Key Generation (DKG)](https://book.arch.network/docs/core-concepts/consensus#distributed-key-generation-dkg) [Distributed Key Generation (DKG) Deep Dive](https://book.arch.network/docs/core-concepts/consensus#distributed-key-generation-dkg-deep-dive) [What is DKG?](https://book.arch.network/docs/core-concepts/consensus#what-is-dkg) [Why DKG is Critical](https://book.arch.network/docs/core-concepts/consensus#why-dkg-is-critical) [The DKG Process Flow](https://book.arch.network/docs/core-concepts/consensus#the-dkg-process-flow) [Phase 1: Network Initialization](https://book.arch.network/docs/core-concepts/consensus#phase-1-network-initialization) [Phase 2: Round 1 - Commitment Generation](https://book.arch.network/docs/core-concepts/consensus#phase-2-round-1---commitment-generation) [Phase 3: Round 2 - Key Generation](https://book.arch.network/docs/core-concepts/consensus#phase-3-round-2---key-generation) [Phase 4: Finalization](https://book.arch.network/docs/core-concepts/consensus#phase-4-finalization) [The `pubkey_package.json` File](https://book.arch.network/docs/core-concepts/consensus#the-pubkey_packagejson-file) [Location and Structure](https://book.arch.network/docs/core-concepts/consensus#location-and-structure) [File Format](https://book.arch.network/docs/core-concepts/consensus#file-format) [What Each Field Represents](https://book.arch.network/docs/core-concepts/consensus#what-each-field-represents) [Key Security Properties](https://book.arch.network/docs/core-concepts/consensus#key-security-properties) [Threshold Signing](https://book.arch.network/docs/core-concepts/consensus#threshold-signing) [Cryptographic Guarantees](https://book.arch.network/docs/core-concepts/consensus#cryptographic-guarantees) [Block Production Process](https://book.arch.network/docs/core-concepts/consensus#block-production-process) [1\. Leader Selection](https://book.arch.network/docs/core-concepts/consensus#1-leader-selection) [2\. Transaction Collection and Verification](https://book.arch.network/docs/core-concepts/consensus#2-transaction-collection-and-verification) [3\. Block Formation](https://book.arch.network/docs/core-concepts/consensus#3-block-formation) [Consensus Process](https://book.arch.network/docs/core-concepts/consensus#consensus-process) [1\. Block Validation](https://book.arch.network/docs/core-concepts/consensus#1-block-validation) [2\. UTXO-Based State Management](https://book.arch.network/docs/core-concepts/consensus#2-utxo-based-state-management) [UTXO State Tracking](https://book.arch.network/docs/core-concepts/consensus#utxo-state-tracking) [State Transition Process](https://book.arch.network/docs/core-concepts/consensus#state-transition-process) [3\. FROST Signing Process](https://book.arch.network/docs/core-concepts/consensus#3-frost-signing-process) [4\. ROAST Enhancement Layer](https://book.arch.network/docs/core-concepts/consensus#4-roast-enhancement-layer) [Asynchronous Operation Guarantees](https://book.arch.network/docs/core-concepts/consensus#asynchronous-operation-guarantees) [Byzantine Fault Tolerance](https://book.arch.network/docs/core-concepts/consensus#byzantine-fault-tolerance) [Understanding FROST](https://book.arch.network/docs/core-concepts/consensus#understanding-frost) [Key Components](https://book.arch.network/docs/core-concepts/consensus#key-components) [Benefits of FROST](https://book.arch.network/docs/core-concepts/consensus#benefits-of-frost) [ROAST: Enhancing FROST for Production](https://book.arch.network/docs/core-concepts/consensus#roast-enhancing-frost-for-production) [Key Enhancements](https://book.arch.network/docs/core-concepts/consensus#key-enhancements) [Security Considerations](https://book.arch.network/docs/core-concepts/consensus#security-considerations) [Threat Model](https://book.arch.network/docs/core-concepts/consensus#threat-model) [Security Properties](https://book.arch.network/docs/core-concepts/consensus#security-properties) [Further Reading](https://book.arch.network/docs/core-concepts/consensus#further-reading) [Academic Papers and Research](https://book.arch.network/docs/core-concepts/consensus#academic-papers-and-research) [FROST (Flexible Round-Optimized Schnorr Threshold Signatures)](https://book.arch.network/docs/core-concepts/consensus#frost-flexible-round-optimized-schnorr-threshold-signatures) [ROAST (Robust Asynchronous Schnorr Threshold Signatures)](https://book.arch.network/docs/core-concepts/consensus#roast-robust-asynchronous-schnorr-threshold-signatures) [Threshold Cryptography and Consensus](https://book.arch.network/docs/core-concepts/consensus#threshold-cryptography-and-consensus) [Technical Resources](https://book.arch.network/docs/core-concepts/consensus#technical-resources) [Implementation Guides](https://book.arch.network/docs/core-concepts/consensus#implementation-guides) [Security Analysis](https://book.arch.network/docs/core-concepts/consensus#security-analysis) [Community Resources](https://book.arch.network/docs/core-concepts/consensus#community-resources) [Conclusion](https://book.arch.network/docs/core-concepts/consensus#conclusion) --- # APL Token Program APL (Arch Program Library) APL Token Program ================= Complete reference for the Arch Program Library Token Program - creating and managing fungible tokens The APL Token Program is the foundation for creating and managing fungible tokens on the Arch Network. This documentation provides a comprehensive guide for developers implementing token functionality in their applications. [Overview](https://book.arch.network/docs/apl/token-program#overview) ---------------------------------------------------------------------- The Token Program enables: * **Creation and management of fungible tokens** (mints) * **Token account management** * **Token transfers and delegations** * **Multisignature authorities** * **Account freezing and thawing** [Program ID](https://book.arch.network/docs/apl/token-program#program-id) -------------------------------------------------------------------------- AplToken111111111111111111111111 [Account Types](https://book.arch.network/docs/apl/token-program#account-types) -------------------------------------------------------------------------------- ### [Mint Account](https://book.arch.network/docs/apl/token-program#mint-account) The central record for a token type, containing: | Field | Type | Description | | --- | --- | --- | | `mint_authority` | `COption` | Optional authority to mint new tokens | | `supply` | `u64` | Total number of tokens in circulation | | `decimals` | `u8` | Number of decimal places | | `is_initialized` | `bool` | Has this mint been initialized | | `freeze_authority` | `COption` | Optional authority to freeze token accounts | ### [Token Account](https://book.arch.network/docs/apl/token-program#token-account) Holds token balances for a specific mint: | Field | Type | Description | | --- | --- | --- | | `mint` | `Pubkey` | The token mint this account holds | | `owner` | `Pubkey` | Owner of this account | | `amount` | `u64` | Number of tokens held | | `delegate` | `COption` | Optional delegate authority | | `state` | `AccountState` | Account state (Uninitialized/Initialized/Frozen) | | `delegated_amount` | `u64` | Amount delegated | | `close_authority` | `COption` | Optional authority to close the account | ### [Multisig Account](https://book.arch.network/docs/apl/token-program#multisig-account) Enables shared authority over token operations: | Field | Type | Description | | --- | --- | --- | | `m` | `u8` | Number of required signers | | `n` | `u8` | Number of valid signers | | `is_initialized` | `bool` | Has this multisig been initialized | | `signers` | `[Pubkey; MAX_SIGNERS]` | Array of valid signer addresses | [Instructions](https://book.arch.network/docs/apl/token-program#instructions) ------------------------------------------------------------------------------ ### [Token Creation and Initialization](https://book.arch.network/docs/apl/token-program#token-creation-and-initialization) #### [InitializeMint](https://book.arch.network/docs/apl/token-program#initializemint) Creates a new token type. pub struct InitializeMint { pub decimals: u8, pub mint_authority: Pubkey, pub freeze_authority: COption, } **Required accounts:** * `[writable]` The mint to initialize **Example:** let mint = Keypair::new(); let mint_authority = Keypair::new(); let decimals = 9; let instruction = apl_token::instruction::initialize_mint( &apl_token::id(), &mint.pubkey(), &mint_authority.pubkey(), None, // No freeze authority decimals, )?; #### [InitializeAccount](https://book.arch.network/docs/apl/token-program#initializeaccount) Creates a new account to hold tokens. **Required accounts:** * `[writable]` The account to initialize * `[]` The mint this account is for * `[]` The owner of the new account **Example:** let account = Keypair::new(); let owner = Keypair::new(); let instruction = apl_token::instruction::initialize_account( &apl_token::id(), &account.pubkey(), &mint.pubkey(), &owner.pubkey(), )?; ### [Token Operations](https://book.arch.network/docs/apl/token-program#token-operations) #### [MintTo](https://book.arch.network/docs/apl/token-program#mintto) Creates new tokens and adds them to a token account. pub struct MintTo { pub amount: u64, } **Required accounts:** * `[writable]` The mint * `[writable]` The destination token account * `[signer]` The mint authority **Example:** let instruction = apl_token::instruction::mint_to( &apl_token::id(), &mint.pubkey(), &destination_account.pubkey(), &mint_authority.pubkey(), &[], 1000000000, // 1 token with 9 decimals )?; #### [Transfer](https://book.arch.network/docs/apl/token-program#transfer) Transfers tokens from one account to another. pub struct Transfer { pub amount: u64, } **Required accounts:** * `[writable]` The source token account * `[writable]` The destination token account * `[signer]` The source account owner **Example:** let instruction = apl_token::instruction::transfer( &apl_token::id(), &source_account.pubkey(), &destination_account.pubkey(), &owner.pubkey(), &[], 500000000, // 0.5 tokens )?; #### [TransferChecked](https://book.arch.network/docs/apl/token-program#transferchecked) Transfers tokens with additional validation. pub struct TransferChecked { pub amount: u64, pub decimals: u8, } **Required accounts:** * `[writable]` The source token account * `[]` The mint * `[writable]` The destination token account * `[signer]` The source account owner **Example:** let instruction = apl_token::instruction::transfer_checked( &apl_token::id(), &source_account.pubkey(), &mint.pubkey(), &destination_account.pubkey(), &owner.pubkey(), &[], 500000000, // 0.5 tokens 9, // decimals )?; ### [Delegation](https://book.arch.network/docs/apl/token-program#delegation) #### [Approve](https://book.arch.network/docs/apl/token-program#approve) Allows a delegate to transfer tokens on behalf of the owner. pub struct Approve { pub amount: u64, } **Required accounts:** * `[writable]` The token account * `[]` The delegate * `[signer]` The account owner **Example:** let delegate = Keypair::new(); let instruction = apl_token::instruction::approve( &apl_token::id(), &token_account.pubkey(), &delegate.pubkey(), &owner.pubkey(), &[], 1000000000, // 1 token )?; #### [Revoke](https://book.arch.network/docs/apl/token-program#revoke) Removes delegation authority. **Required accounts:** * `[writable]` The token account * `[signer]` The account owner **Example:** let instruction = apl_token::instruction::revoke( &apl_token::id(), &token_account.pubkey(), &owner.pubkey(), &[], )?; ### [Account Management](https://book.arch.network/docs/apl/token-program#account-management) #### [FreezeAccount](https://book.arch.network/docs/apl/token-program#freezeaccount) Freezes a token account, preventing transfers. **Required accounts:** * `[writable]` The token account * `[]` The mint * `[signer]` The freeze authority **Example:** let instruction = apl_token::instruction::freeze_account( &apl_token::id(), &token_account.pubkey(), &mint.pubkey(), &freeze_authority.pubkey(), &[], )?; #### [ThawAccount](https://book.arch.network/docs/apl/token-program#thawaccount) Unfreezes a frozen token account. **Required accounts:** * `[writable]` The token account * `[]` The mint * `[signer]` The freeze authority **Example:** let instruction = apl_token::instruction::thaw_account( &apl_token::id(), &token_account.pubkey(), &mint.pubkey(), &freeze_authority.pubkey(), &[], )?; #### [CloseAccount](https://book.arch.network/docs/apl/token-program#closeaccount) Closes a token account and reclaims rent. **Required accounts:** * `[writable]` The token account * `[writable]` The destination for reclaimed rent * `[signer]` The account owner **Example:** let instruction = apl_token::instruction::close_account( &apl_token::id(), &token_account.pubkey(), &destination_account.pubkey(), &owner.pubkey(), &[], )?; ### [Multisig Operations](https://book.arch.network/docs/apl/token-program#multisig-operations) #### [InitializeMultisig](https://book.arch.network/docs/apl/token-program#initializemultisig) Creates a multisig account for shared authority. pub struct InitializeMultisig { pub m: u8, // Required signatures } **Required accounts:** * `[writable]` The multisig account * `[]` The rent sysvar **Example:** let multisig = Keypair::new(); let signers = vec![signer1.pubkey(), signer2.pubkey(), signer3.pubkey()]; let instruction = apl_token::instruction::initialize_multisig( &apl_token::id(), &multisig.pubkey(), &signers, 2, // Require 2 of 3 signatures )?; [Error Codes](https://book.arch.network/docs/apl/token-program#error-codes) ---------------------------------------------------------------------------- | Code | Name | Description | | --- | --- | --- | | 0 | `InvalidMint` | The mint provided is not valid | | 1 | `InvalidOwner` | The owner provided is not valid | | 2 | `InvalidAmount` | The amount provided is not valid | | 3 | `InvalidDelegate` | The delegate provided is not valid | | 4 | `InvalidAccount` | The account provided is not valid | | 5 | `InvalidState` | The account state is not valid | | 6 | `InvalidAuthority` | The authority provided is not valid | | 7 | `InvalidCloseAuthority` | The close authority provided is not valid | | 8 | `InvalidFreezeAuthority` | The freeze authority provided is not valid | | 9 | `InvalidMintAuthority` | The mint authority provided is not valid | | 10 | `InvalidSupply` | The supply provided is not valid | | 11 | `InvalidDecimals` | The decimals provided are not valid | | 12 | `InvalidInstruction` | The instruction provided is not valid | | 13 | `InvalidProgramId` | The program ID provided is not valid | | 14 | `InvalidAccountData` | The account data provided is not valid | | 15 | `InvalidAccountOwner` | The account owner provided is not valid | | 16 | `InvalidAccountDataLength` | The account data length is not valid | | 17 | `InvalidAccountDataFormat` | The account data format is not valid | | 18 | `InvalidAccountDataVersion` | The account data version is not valid | | 19 | `InvalidAccountDataDiscriminator` | The account data discriminator is not valid | [Usage Examples](https://book.arch.network/docs/apl/token-program#usage-examples) ---------------------------------------------------------------------------------- ### [Creating a Token](https://book.arch.network/docs/apl/token-program#creating-a-token) use arch_sdk::prelude::*; use apl_token::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Connect to Arch Network let client = ArchNetworkClient::new("http://localhost:9002").await?; // Create keypairs let mint_keypair = Keypair::new(); let mint_authority = Keypair::new(); let payer = Keypair::new(); // Create mint account let mint_account = client.create_account( CreateAccountParams { space: apl_token::state::Mint::LEN, // Mint account size owner: apl_token::id(), payer: &payer, } ).await?; // Initialize mint let instruction = initialize_mint( &apl_token::id(), &mint_account.pubkey(), &mint_authority.pubkey(), None, // No freeze authority 9, // 9 decimals )?; // Send transaction let transaction = Transaction::new() .add_instruction(instruction); let signature = client.send_transaction(transaction, &[&payer, &mint_authority]).await?; println!("Mint created: {}", signature); Ok(()) } ### [Creating a Token Account](https://book.arch.network/docs/apl/token-program#creating-a-token-account) async fn create_token_account( client: &ArchNetworkClient, mint: &Pubkey, owner: &Pubkey, payer: &Keypair, ) -> Result> { // Create account let account = client.create_account( CreateAccountParams { space: apl_token::state::Account::LEN, // Token account size owner: apl_token::id(), payer, } ).await?; // Initialize account let instruction = initialize_account( &apl_token::id(), &account.pubkey(), mint, owner, )?; // Send transaction let transaction = Transaction::new() .add_instruction(instruction); client.send_transaction(transaction, &[payer]).await?; Ok(account.pubkey()) } ### [Minting Tokens](https://book.arch.network/docs/apl/token-program#minting-tokens) async fn mint_tokens( client: &ArchNetworkClient, mint: &Pubkey, destination: &Pubkey, amount: u64, mint_authority: &Keypair, payer: &Keypair, ) -> Result<(), Box> { let instruction = mint_to( &apl_token::id(), mint, destination, &mint_authority.pubkey(), &[], amount, )?; let transaction = Transaction::new() .add_instruction(instruction); client.send_transaction(transaction, &[mint_authority, payer]).await?; Ok(()) } ### [Transferring Tokens](https://book.arch.network/docs/apl/token-program#transferring-tokens) async fn transfer_tokens( client: &ArchNetworkClient, source: &Pubkey, destination: &Pubkey, amount: u64, owner: &Keypair, payer: &Keypair, ) -> Result<(), Box> { let instruction = transfer( &apl_token::id(), source, destination, &owner.pubkey(), &[], amount, )?; let transaction = Transaction::new() .add_instruction(instruction); client.send_transaction(transaction, &[owner, payer]).await?; Ok(()) } [CLI Usage](https://book.arch.network/docs/apl/token-program#cli-usage) ------------------------------------------------------------------------ ### [Create a Token Mint](https://book.arch.network/docs/apl/token-program#create-a-token-mint) # Create a new token mint arch-cli token create-mint \ --decimals 9 \ --mint-authority ~/mint_authority.key \ --keypair-path ~/payer.key ### [Create a Token Account](https://book.arch.network/docs/apl/token-program#create-a-token-account) # Create a token account arch-cli token create-account \ --mint \ --owner ~/owner.key \ --keypair-path ~/payer.key ### [Mint Tokens](https://book.arch.network/docs/apl/token-program#mint-tokens) # Mint tokens to an account arch-cli token mint-to \ --mint \ --destination \ --amount 1000000000 \ --mint-authority ~/mint_authority.key \ --keypair-path ~/payer.key ### [Transfer Tokens](https://book.arch.network/docs/apl/token-program#transfer-tokens) # Transfer tokens between accounts arch-cli token transfer \ --source \ --destination \ --amount 500000000 \ --owner ~/owner.key \ --keypair-path ~/payer.key [Best Practices](https://book.arch.network/docs/apl/token-program#best-practices) ---------------------------------------------------------------------------------- ### [Security](https://book.arch.network/docs/apl/token-program#security) 1. **Secure Key Management**: Store private keys securely and never share them 2. **Use Multisig**: Implement multisig for important operations 3. **Regular Audits**: Regularly audit token operations and balances 4. **Access Control**: Implement proper access controls for mint authorities ### [Performance](https://book.arch.network/docs/apl/token-program#performance) 1. **Batch Operations**: Use batch operations for multiple transfers 2. **Account Management**: Close unused accounts to reclaim rent 3. **Efficient Decimals**: Choose appropriate decimal places for your use case 4. **Monitor Gas**: Monitor transaction costs and optimize accordingly ### [Development](https://book.arch.network/docs/apl/token-program#development) 1. **Test Thoroughly**: Test all operations in development before production 2. **Error Handling**: Implement proper error handling in your applications 3. **Documentation**: Document your token's purpose and operations 4. **Community**: Follow community best practices and standards [Next Steps](https://book.arch.network/docs/apl/token-program#next-steps) -------------------------------------------------------------------------- [### Associated Token Account\ \ Learn about associated token accounts](https://book.arch.network/docs/APL/associated-token-account) [### Token Guide\ \ Complete guide to creating tokens](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### SDK Reference\ \ Learn to use the SDKs](https://book.arch.network/docs/tools-apis/sdk) [### Examples\ \ Explore example implementations](https://github.com/Arch-Network/arch-examples) [Resources](https://book.arch.network/docs/apl/token-program#resources) ------------------------------------------------------------------------ [### Token Guide\ \ Step-by-step token creation guide](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [### CLI Reference\ \ Complete CLI command reference](https://book.arch.network/docs/tools-apis/arch-cli-reference) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [Introduction to the Arch Program Library (APL)\ \ A collection of on-chain programs providing fundamental building blocks for Arch Network dApps](https://book.arch.network/docs/apl/introduction) [Bitcoin Integration\ \ How Arch Network integrates with Bitcoin through UTXO management and RPC interfaces](https://book.arch.network/docs/core-concepts/bitcoin-integration) ### On this page [Overview](https://book.arch.network/docs/apl/token-program#overview) [Program ID](https://book.arch.network/docs/apl/token-program#program-id) [Account Types](https://book.arch.network/docs/apl/token-program#account-types) [Mint Account](https://book.arch.network/docs/apl/token-program#mint-account) [Token Account](https://book.arch.network/docs/apl/token-program#token-account) [Multisig Account](https://book.arch.network/docs/apl/token-program#multisig-account) [Instructions](https://book.arch.network/docs/apl/token-program#instructions) [Token Creation and Initialization](https://book.arch.network/docs/apl/token-program#token-creation-and-initialization) [InitializeMint](https://book.arch.network/docs/apl/token-program#initializemint) [InitializeAccount](https://book.arch.network/docs/apl/token-program#initializeaccount) [Token Operations](https://book.arch.network/docs/apl/token-program#token-operations) [MintTo](https://book.arch.network/docs/apl/token-program#mintto) [Transfer](https://book.arch.network/docs/apl/token-program#transfer) [TransferChecked](https://book.arch.network/docs/apl/token-program#transferchecked) [Delegation](https://book.arch.network/docs/apl/token-program#delegation) [Approve](https://book.arch.network/docs/apl/token-program#approve) [Revoke](https://book.arch.network/docs/apl/token-program#revoke) [Account Management](https://book.arch.network/docs/apl/token-program#account-management) [FreezeAccount](https://book.arch.network/docs/apl/token-program#freezeaccount) [ThawAccount](https://book.arch.network/docs/apl/token-program#thawaccount) [CloseAccount](https://book.arch.network/docs/apl/token-program#closeaccount) [Multisig Operations](https://book.arch.network/docs/apl/token-program#multisig-operations) [InitializeMultisig](https://book.arch.network/docs/apl/token-program#initializemultisig) [Error Codes](https://book.arch.network/docs/apl/token-program#error-codes) [Usage Examples](https://book.arch.network/docs/apl/token-program#usage-examples) [Creating a Token](https://book.arch.network/docs/apl/token-program#creating-a-token) [Creating a Token Account](https://book.arch.network/docs/apl/token-program#creating-a-token-account) [Minting Tokens](https://book.arch.network/docs/apl/token-program#minting-tokens) [Transferring Tokens](https://book.arch.network/docs/apl/token-program#transferring-tokens) [CLI Usage](https://book.arch.network/docs/apl/token-program#cli-usage) [Create a Token Mint](https://book.arch.network/docs/apl/token-program#create-a-token-mint) [Create a Token Account](https://book.arch.network/docs/apl/token-program#create-a-token-account) [Mint Tokens](https://book.arch.network/docs/apl/token-program#mint-tokens) [Transfer Tokens](https://book.arch.network/docs/apl/token-program#transfer-tokens) [Best Practices](https://book.arch.network/docs/apl/token-program#best-practices) [Security](https://book.arch.network/docs/apl/token-program#security) [Performance](https://book.arch.network/docs/apl/token-program#performance) [Development](https://book.arch.network/docs/apl/token-program#development) [Next Steps](https://book.arch.network/docs/apl/token-program#next-steps) [Resources](https://book.arch.network/docs/apl/token-program#resources) --- # RPC Reference Reference RPC Reference ============= [RPC Reference](https://book.arch.network/docs/reference/rpc#rpc-reference) ============================================================================ This section documents Arch's HTTP RPC methods. Methods are grouped by category to make it easy to find what you need. [Categories](https://book.arch.network/docs/reference/rpc#categories) ---------------------------------------------------------------------- * Node Status * get-version * is-node-ready * get-peers * get-best-block-hash * get-best-finalized-block-hash * get-block-count * Blocks * get-block-hash * get-block * Accounts * get-account-address * get-all-accounts * read-account-info * get-program-accounts * Transactions * send-transaction * send-transactions * get-processed-transaction * get-transaction-report * get-latest-tx-using-account * get-arch-txid-from-btc-txid * Network/State * get-current-state * get-network-pubkey * reset-network * start-dkg > See method pages in the subfolders for details and request/response examples. [System Requirements\ \ Hardware and software requirements for Arch Network development](https://book.arch.network/docs/quick-start/requirements) [SDK Reference\ \ Next Page](https://book.arch.network/docs/sdk) ### On this page [RPC Reference](https://book.arch.network/docs/reference/rpc#rpc-reference) [Categories](https://book.arch.network/docs/reference/rpc#categories) --- # Getting Started with the TypeScript SDK [SDK](https://book.arch.network/docs/sdk) Typescript Getting Started with the TypeScript SDK ======================================= [Getting Started with the TypeScript SDK](https://book.arch.network/docs/sdk/typescript/getting-started#getting-started-with-the-typescript-sdk) ================================================================================================================================================= This guide will walk you through setting up and using the Arch Network TypeScript SDK (developed by Saturn) to build your first application. > **Note**: The Arch TypeScript SDK is a low-level SDK that provides direct RPC access to Arch nodes. It does not include high-level abstractions like transaction builders or wallet management. [Prerequisites](https://book.arch.network/docs/sdk/typescript/getting-started#prerequisites) --------------------------------------------------------------------------------------------- * **Node.js 16+** and npm or yarn * **Basic understanding** of blockchain concepts and JavaScript/TypeScript * **Arch Network node** running locally or access to a remote node [Installation](https://book.arch.network/docs/sdk/typescript/getting-started#installation) ------------------------------------------------------------------------------------------- ### [Create a New Project](https://book.arch.network/docs/sdk/typescript/getting-started#create-a-new-project) # Create a new project mkdir my-arch-app cd my-arch-app npm init -y # Install the Saturn TypeScript SDK npm install @saturnbtcio/arch-sdk # Install TypeScript (optional but recommended) npm install -D typescript @types/node npx tsc --init ### [For Existing Projects](https://book.arch.network/docs/sdk/typescript/getting-started#for-existing-projects) # Using npm npm install @saturnbtcio/arch-sdk # Using yarn yarn add @saturnbtcio/arch-sdk # Using pnpm pnpm add @saturnbtcio/arch-sdk [Your First Connection](https://book.arch.network/docs/sdk/typescript/getting-started#your-first-connection) ------------------------------------------------------------------------------------------------------------- Create a file named `connect.ts` (or `connect.js` for JavaScript): import { RpcConnection } from '@saturnbtcio/arch-sdk'; async function main() { // Connect to local validator const connection = new RpcConnection('http://localhost:9002'); try { console.log('πŸ”Œ Connecting to Arch node at http://localhost:9002...\n'); // Get current block count const blockCount = await connection.getBlockCount(); console.log('βœ“ Current block count:', blockCount); // Get best block hash const bestBlockHash = await connection.getBestBlockHash(); console.log('βœ“ Best block hash:', bestBlockHash); // Get block hash for a specific height if (blockCount > 0) { const blockHeight = blockCount - 1; const blockHash = await connection.getBlockHash(blockHeight); console.log(`βœ“ Block hash at height ${blockHeight}:`, blockHash); } console.log('\nβœ… Successfully connected to Arch node!'); console.log('πŸ“Š Network is active with', blockCount, 'blocks'); } catch (error) { console.error('❌ Error connecting to Arch node:', error); console.log('\nπŸ’‘ Make sure your Arch node is running at http://localhost:9002'); console.log(' You can start it with: arch-node --network=testnet'); } } // Run the main function main().catch(console.error); Run the script: # TypeScript npx ts-node connect.ts # JavaScript node connect.js Example output: Connecting to Arch node at http://localhost:9002... βœ“ Current block count: 57230 βœ“ Best block hash: 349e8a42cdc98d05d427ba8fe8efcfd13e875591f1f1f111960a991f3add8105 βœ“ Block hash at height 57229: 349e8a42cdc98d05d427ba8fe8efcfd13e875591f1f1f111960a991f3add8105 βœ… Successfully connected to Arch node! πŸ“Š Network is active with 57230 blocks [Creating Accounts](https://book.arch.network/docs/sdk/typescript/getting-started#creating-accounts) ----------------------------------------------------------------------------------------------------- The SDK provides utilities for creating accounts using secp256k1 cryptography: import { RpcConnection, ArchConnection } from '@saturnbtcio/arch-sdk'; async function createAccount() { const connection = new RpcConnection('http://localhost:9002'); const arch = ArchConnection(connection); // Create a new account const account = await arch.createNewAccount(); console.log('πŸ”‘ New Account Created:'); console.log('Private Key:', account.privkey); console.log('Public Key:', account.pubkey); console.log('Address:', account.address); return account; } createAccount().catch(console.error); ### [Create Account with Faucet Funding](https://book.arch.network/docs/sdk/typescript/getting-started#create-account-with-faucet-funding) import { RpcConnection } from '@saturnbtcio/arch-sdk'; import { randomBytes } from 'node:crypto'; // Helper function to wait for a specified time const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); async function createAndFundAccount() { const connection = new RpcConnection('http://localhost:9002'); try { console.log('πŸ”Œ Connecting to Arch node...\n'); // Check the current block height const initialBlockCount = await connection.getBlockCount(); console.log('πŸ“Š Current block height:', initialBlockCount); // Generate a random 32-byte public key const pubkey = randomBytes(32); console.log('πŸ”‘ Generated public key:', pubkey.toString('hex')); // Create account with faucet console.log('\nπŸ’° Step 1: Creating account with faucet...'); await connection.createAccountWithFaucet(pubkey); console.log('βœ… Faucet account creation initiated'); // Get the Arch address const archAddress = await connection.getAccountAddress(pubkey); console.log('πŸ“ Arch address:', archAddress); // Request airdrop to fund the account console.log('\nπŸ’° Step 2: Requesting airdrop...'); await connection.requestAirdrop(pubkey); console.log('βœ… Airdrop requested'); // Wait for account to be created and funded console.log('\n⏳ Waiting for account to be confirmed on chain...'); console.log(' (This may take 5-10 seconds)'); let accountFound = false; const maxAttempts = 6; for (let attempt = 1; attempt <= maxAttempts; attempt++) { const waitTime = attempt * 2000; // Increase wait time each attempt console.log(`\nπŸ”„ Attempt ${attempt}/${maxAttempts}: Waiting ${waitTime / 1000} seconds...`); await wait(waitTime); // Check block progress const currentBlockCount = await connection.getBlockCount(); console.log(`πŸ“ˆ Blocks produced: ${currentBlockCount - initialBlockCount}`); try { const accountInfo = await connection.readAccountInfo(pubkey); console.log('\nβœ… Account successfully created and funded!'); console.log('\nπŸ“Š Account Details:'); console.log(' Address:', archAddress); console.log(' Full info:', JSON.stringify(accountInfo, null, 2)); // Access properties safely const info = accountInfo as any; if (info.lamports !== undefined) { console.log(' Balance:', info.lamports, 'lamports'); } if (info.owner) { console.log(' Owner:', Buffer.from(Object.values(info.owner)).toString('hex')); } if (info.utxo) { console.log(' UTXO:', info.utxo); } if (info.is_executable !== undefined) { console.log(' Executable:', info.is_executable); } accountFound = true; break; } catch (error) { if (attempt === maxAttempts) { console.log('❌ Account not found after maximum attempts'); } else { console.log('⏳ Account not ready yet, continuing to wait...'); } } } if (accountFound) { console.log('\nπŸŽ‰ Success! Your Arch account is ready to use.'); console.log('πŸ’‘ You can now:'); console.log(' - Send transactions from this account'); console.log(' - Interact with Arch programs'); console.log(' - Deploy smart contracts'); console.log('\nπŸ“ Save these for future reference:'); console.log(' Pubkey:', pubkey.toString('hex')); console.log(' Address:', archAddress); } } catch (error) { console.error('❌ Error:', error); console.log('\nπŸ’‘ Troubleshooting:'); console.log(' - Make sure your Arch node is running at http://localhost:9002'); console.log(' - Ensure the node has faucet functionality enabled'); console.log(' - Check that the node is syncing and producing blocks'); } } createAndFundAccount(); [Reading Account Information](https://book.arch.network/docs/sdk/typescript/getting-started#reading-account-information) ------------------------------------------------------------------------------------------------------------------------- import { RpcConnection } from '@saturnbtcio/arch-sdk'; async function readAccount() { const connection = new RpcConnection('http://localhost:9002'); // Example: System program pubkey (32 zero bytes with last byte as 1) const systemProgramPubkey = new Uint8Array(32); systemProgramPubkey[31] = 1; try { const accountInfo = await connection.readAccountInfo(systemProgramPubkey); console.log('Account Info:', accountInfo); // Get account address const address = await connection.getAccountAddress(systemProgramPubkey); console.log('Account Address:', address); } catch (error) { console.error('Error reading account:', error); } } [Working with Messages and Instructions](https://book.arch.network/docs/sdk/typescript/getting-started#working-with-messages-and-instructions) ----------------------------------------------------------------------------------------------------------------------------------------------- The SDK uses a low-level message format for transactions: import { RpcConnection, InstructionUtil, MessageUtil, PubkeyUtil } from '@saturnbtcio/arch-sdk'; import type { Message, Instruction } from '@saturnbtcio/arch-sdk'; // Create a simple instruction const instruction: Instruction = { program_id: PubkeyUtil.systemProgram(), // Returns system program pubkey accounts: [\ {\ pubkey: new Uint8Array(32), // Your account pubkey\ is_signer: true,\ is_writable: true,\ },\ ], data: new Uint8Array([1, 2, 3, 4]), // Instruction data }; // Create a message const message: Message = { signers: [new Uint8Array(32)], // Array of signer pubkeys instructions: [instruction], }; // Serialize the message for sending const serializedMessage = MessageUtil.serialize(message); console.log('Serialized message:', serializedMessage); [Sending Transactions](https://book.arch.network/docs/sdk/typescript/getting-started#sending-transactions) ----------------------------------------------------------------------------------------------------------- To send transactions, you need to create a `RuntimeTransaction`: import { RpcConnection, PubkeyUtil } from '@saturnbtcio/arch-sdk'; import type { RuntimeTransaction, SanitizedMessage } from '@saturnbtcio/arch-sdk'; async function sendTransaction() { const connection = new RpcConnection('http://localhost:9002'); // Note: Creating valid transactions requires proper message construction // and cryptographic signatures. This is a simplified example. const sanitizedMessage: SanitizedMessage = { header: { num_required_signatures: 1, num_readonly_signed_accounts: 0, num_readonly_unsigned_accounts: 0, }, account_keys: [\ new Uint8Array(32), // Signer pubkey\ PubkeyUtil.systemProgram(), // System program\ ], recent_blockhash: new Uint8Array(32), // Recent blockhash instructions: [\ {\ program_id_index: 1, // Index into account_keys\ accounts: [0], // Indexes into account_keys\ data: new Uint8Array([1, 2, 3, 4]),\ },\ ], }; const transaction: RuntimeTransaction = { version: 0, signatures: [new Uint8Array(64)], // 64-byte signatures message: sanitizedMessage, }; try { const txId = await connection.sendTransaction(transaction); console.log('Transaction sent:', txId); } catch (error) { console.error('Error sending transaction:', error); } } [Querying Blocks](https://book.arch.network/docs/sdk/typescript/getting-started#querying-blocks) ------------------------------------------------------------------------------------------------- import { RpcConnection } from '@saturnbtcio/arch-sdk'; async function queryBlocks() { const connection = new RpcConnection('http://localhost:9002'); try { // Get the latest block const bestBlockHash = await connection.getBestBlockHash(); const block = await connection.getBlock(bestBlockHash); if (block) { console.log('Block:', block); console.log('Number of transactions:', block.transactions?.length || 0); } } catch (error) { console.error('Error querying blocks:', error); } } [Get Processed Transaction](https://book.arch.network/docs/sdk/typescript/getting-started#get-processed-transaction) --------------------------------------------------------------------------------------------------------------------- import { RpcConnection } from '@saturnbtcio/arch-sdk'; async function getTransaction(txId: string) { const connection = new RpcConnection('http://localhost:9002'); try { const processedTx = await connection.getProcessedTransaction(txId); if (processedTx) { console.log('Transaction found:', processedTx); console.log('Status:', processedTx.status); } else { console.log('Transaction not found'); } } catch (error) { console.error('Error getting transaction:', error); } } [Get Program Accounts](https://book.arch.network/docs/sdk/typescript/getting-started#get-program-accounts) ----------------------------------------------------------------------------------------------------------- import { RpcConnection } from '@saturnbtcio/arch-sdk'; async function getProgramAccounts() { const connection = new RpcConnection('http://localhost:9002'); // Example: Get all accounts owned by a program const programId = new Uint8Array(32); // Your program ID try { const accounts = await connection.getProgramAccounts(programId); console.log(`Found ${accounts.length} accounts for program`); accounts.forEach((account, index) => { console.log(`Account ${index}:`, account); }); } catch (error) { console.error('Error getting program accounts:', error); } } [Utility Functions](https://book.arch.network/docs/sdk/typescript/getting-started#utility-functions) ----------------------------------------------------------------------------------------------------- The SDK provides several utility modules for working with Arch data structures: import { PubkeyUtil, MessageUtil, InstructionUtil, AccountUtil, SignatureUtil } from '@saturnbtcio/arch-sdk'; // Get system program pubkey const systemProgram = PubkeyUtil.systemProgram(); // Work with public keys const pubkeyBytes = new Uint8Array(32); const pubkeyHex = PubkeyUtil.toHex(pubkeyBytes); const pubkeyFromHex = PubkeyUtil.fromHex(pubkeyHex); // Serialize/deserialize messages const serializedMsg = MessageUtil.serialize(message); const deserializedMsg = MessageUtil.deserialize(serializedMsg); [Error Handling](https://book.arch.network/docs/sdk/typescript/getting-started#error-handling) ----------------------------------------------------------------------------------------------- The SDK provides custom error types: import { RpcConnection, ArchRpcError } from '@saturnbtcio/arch-sdk'; async function handleErrors() { const connection = new RpcConnection('http://localhost:9002'); try { await connection.getBlock('invalid-hash'); } catch (error) { if (error instanceof ArchRpcError) { console.error('RPC Error:', error.error); console.error('Error code:', error.error.code); console.error('Error message:', error.error.message); } else { console.error('Unexpected error:', error); } } } [Complete Example](https://book.arch.network/docs/sdk/typescript/getting-started#complete-example) --------------------------------------------------------------------------------------------------- Here's a complete example showing how to connect and query the network: import { RpcConnection, ArchConnection } from '@saturnbtcio/arch-sdk'; async function completeExample() { // 1. Setup connection const connection = new RpcConnection('http://localhost:9002'); const arch = ArchConnection(connection); try { // 2. Get network info console.log('πŸ“Š Network Information:'); const blockCount = await connection.getBlockCount(); console.log('Block count:', blockCount); const bestBlockHash = await connection.getBestBlockHash(); console.log('Best block hash:', bestBlockHash); // 3. Create a new account console.log('\nπŸ”‘ Creating new account...'); const account = await arch.createNewAccount(); console.log('Address:', account.address); // 4. Get block information if (blockCount > 0) { const blockHash = await connection.getBlockHash(blockCount - 1); const block = await connection.getBlock(blockHash); if (block) { console.log('\nπŸ“¦ Latest block:'); console.log('Hash:', blockHash); console.log('Transactions:', block.transactions?.length || 0); } } console.log('\nβœ… Example completed successfully!'); } catch (error) { console.error('❌ Error:', error); } } completeExample().catch(console.error); [Important Notes](https://book.arch.network/docs/sdk/typescript/getting-started#important-notes) ------------------------------------------------------------------------------------------------- 1. **Low-Level SDK**: This SDK provides low-level RPC access. High-level features like transaction building, wallet management, and program deployment helpers are not included. 2. **Message Construction**: Creating valid transactions requires proper understanding of Arch's message format and cryptographic signatures. 3. **Type Safety**: The SDK is written in TypeScript and provides type definitions for all data structures. 4. **Error Handling**: Always wrap RPC calls in try-catch blocks as network operations can fail. [Next Steps](https://book.arch.network/docs/sdk/typescript/getting-started#next-steps) --------------------------------------------------------------------------------------- * Learn about [Arch's account model](https://book.arch.network/docs/sdk/account.md) * Understand [message and instruction formats](https://book.arch.network/docs/sdk/instructions-and-messages.md) * Explore the [RPC API](https://book.arch.network/docs/reference/rpc) for all available methods * Check the [TypeScript SDK source](https://github.com/saturnbtc/arch-typescript-sdk) for implementation details [Resources](https://book.arch.network/docs/sdk/typescript/getting-started#resources) ------------------------------------------------------------------------------------- * **NPM Package**: [@saturnbtcio/arch-sdk](https://www.npmjs.com/package/@saturnbtcio/arch-sdk) * **GitHub Repository**: [saturnbtc/arch-typescript-sdk](https://github.com/saturnbtc/arch-typescript-sdk) * **Discord**: [Arch Network Discord](https://discord.gg/archnetwork) [SDK Reference\ \ Previous Page](https://book.arch.network/docs/sdk) [Architecture Overview\ \ Understanding the core components and architecture of Arch Network](https://book.arch.network/docs/setup-infrastructure/architecture) ### On this page [Getting Started with the TypeScript SDK](https://book.arch.network/docs/sdk/typescript/getting-started#getting-started-with-the-typescript-sdk) [Prerequisites](https://book.arch.network/docs/sdk/typescript/getting-started#prerequisites) [Installation](https://book.arch.network/docs/sdk/typescript/getting-started#installation) [Create a New Project](https://book.arch.network/docs/sdk/typescript/getting-started#create-a-new-project) [For Existing Projects](https://book.arch.network/docs/sdk/typescript/getting-started#for-existing-projects) [Your First Connection](https://book.arch.network/docs/sdk/typescript/getting-started#your-first-connection) [Creating Accounts](https://book.arch.network/docs/sdk/typescript/getting-started#creating-accounts) [Create Account with Faucet Funding](https://book.arch.network/docs/sdk/typescript/getting-started#create-account-with-faucet-funding) [Reading Account Information](https://book.arch.network/docs/sdk/typescript/getting-started#reading-account-information) [Working with Messages and Instructions](https://book.arch.network/docs/sdk/typescript/getting-started#working-with-messages-and-instructions) [Sending Transactions](https://book.arch.network/docs/sdk/typescript/getting-started#sending-transactions) [Querying Blocks](https://book.arch.network/docs/sdk/typescript/getting-started#querying-blocks) [Get Processed Transaction](https://book.arch.network/docs/sdk/typescript/getting-started#get-processed-transaction) [Get Program Accounts](https://book.arch.network/docs/sdk/typescript/getting-started#get-program-accounts) [Utility Functions](https://book.arch.network/docs/sdk/typescript/getting-started#utility-functions) [Error Handling](https://book.arch.network/docs/sdk/typescript/getting-started#error-handling) [Complete Example](https://book.arch.network/docs/sdk/typescript/getting-started#complete-example) [Important Notes](https://book.arch.network/docs/sdk/typescript/getting-started#important-notes) [Next Steps](https://book.arch.network/docs/sdk/typescript/getting-started#next-steps) [Resources](https://book.arch.network/docs/sdk/typescript/getting-started#resources) --- # FAQ Help Resources FAQ === Frequently asked questions about Arch Network development [General Questions](https://book.arch.network/docs/help-resources/faq#general-questions) ----------------------------------------------------------------------------------------- ### [What is Arch Network?](https://book.arch.network/docs/help-resources/faq#what-is-arch-network) Arch Network is a Bitcoin-native computation environment that enables smart contracts and decentralized applications while maintaining direct integration with Bitcoin's security model. Unlike Layer 2 solutions, Arch Network provides a native computation layer that works directly with Bitcoin UTXOs. ### [How is Arch Network different from other blockchain platforms?](https://book.arch.network/docs/help-resources/faq#how-is-arch-network-different-from-other-blockchain-platforms) Arch Network is unique because it: * **Bitcoin-Native**: Direct integration with Bitcoin's UTXO model * **No Token Required**: Uses Bitcoin for transaction fees and security * **Threshold Signatures**: Uses ROAST/FROST consensus for security * **Programmable**: Supports smart contracts written in Rust * **Scalable**: Efficient state management and parallel processing ### [What programming languages are supported?](https://book.arch.network/docs/help-resources/faq#what-programming-languages-are-supported) Currently, Arch Network supports: * **Rust**: Primary language for smart contract development * **TypeScript/JavaScript**: For client applications and SDK usage * **Future**: Additional languages may be added based on community demand [Development Questions](https://book.arch.network/docs/help-resources/faq#development-questions) ------------------------------------------------------------------------------------------------- ### [How do I get started with Arch Network development?](https://book.arch.network/docs/help-resources/faq#how-do-i-get-started-with-arch-network-development) 1. **Install Prerequisites**: Rust, Solana CLI, Arch CLI, and Docker 2. **Set up Local Environment**: Use `arch-cli orchestrate start` for automated setup 3. **Write Your First Program**: Follow our [Writing Your First Program guide](https://book.arch.network/docs/development/writing-your-first-program) 4. **Deploy and Test**: Use the local validator for testing ### [What tools do I need for development?](https://book.arch.network/docs/help-resources/faq#what-tools-do-i-need-for-development) Essential tools: * **Rust**: For smart contract development * **Solana CLI**: For program compilation * **Arch CLI**: For deployment and testing * **Docker**: For running the complete stack locally * **VS Code**: Recommended IDE with Rust extensions ### [How do I test my programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-test-my-programs) You can test your programs using: * **Local Validator**: Run `arch-cli orchestrate start` for a complete local environment * **Unit Tests**: Write Rust tests for your program logic * **Integration Tests**: Test with the full validator stack * **Client Applications**: Build TypeScript/JavaScript clients [Technical Questions](https://book.arch.network/docs/help-resources/faq#technical-questions) --------------------------------------------------------------------------------------------- ### [How does Arch Network integrate with Bitcoin?](https://book.arch.network/docs/help-resources/faq#how-does-arch-network-integrate-with-bitcoin) Arch Network integrates with Bitcoin through: * **UTXO Management**: Direct interaction with Bitcoin UTXOs * **State Anchoring**: Program state is anchored to Bitcoin transactions * **Threshold Signatures**: Uses Bitcoin-compatible Schnorr signatures * **RPC Integration**: Communicates with Bitcoin nodes via RPC ### [What is the consensus mechanism?](https://book.arch.network/docs/help-resources/faq#what-is-the-consensus-mechanism) Arch Network uses a combination of: * **ROAST**: Robust Asynchronous Schnorr Threshold Signatures * **FROST**: Flexible Round-Optimized Schnorr Threshold Signatures * **DKG**: Distributed Key Generation for validator coordination * **Bitcoin Finality**: Leverages Bitcoin's security guarantees ### [How do I handle Bitcoin transactions in my programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-handle-bitcoin-transactions-in-my-programs) You can interact with Bitcoin transactions through: * **UTXO Operations**: Create, spend, and manage UTXOs * **Transaction Validation**: Verify Bitcoin transaction signatures * **State Transitions**: Update program state based on Bitcoin events * **RPC Calls**: Query Bitcoin network state [Deployment Questions](https://book.arch.network/docs/help-resources/faq#deployment-questions) ----------------------------------------------------------------------------------------------- ### [How do I deploy my program to the network?](https://book.arch.network/docs/help-resources/faq#how-do-i-deploy-my-program-to-the-network) 1. **Build Your Program**: Use `cargo build-sbf` to compile 2. **Deploy Locally**: Use `arch-cli deploy` for local testing 3. **Testnet Deployment**: Deploy to testnet for broader testing 4. **Mainnet Deployment**: Deploy to mainnet (when available) ### [What networks are available?](https://book.arch.network/docs/help-resources/faq#what-networks-are-available) Currently available: * **Regtest**: Local development network * **Testnet**: Public test network with real Bitcoin testnet * **Mainnet**: Production network (coming soon) ### [How do I interact with deployed programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-interact-with-deployed-programs) You can interact with programs using: * **Arch CLI**: Command-line interface for basic operations * **TypeScript SDK**: For building web applications * **Rust SDK**: For building Rust applications * **RPC API**: Direct API calls for custom integrations [Troubleshooting Questions](https://book.arch.network/docs/help-resources/faq#troubleshooting-questions) --------------------------------------------------------------------------------------------------------- ### [My program won't compile. What should I check?](https://book.arch.network/docs/help-resources/faq#my-program-wont-compile-what-should-i-check) Common compilation issues: * **Rust Version**: Ensure you're using the latest stable Rust * **Dependencies**: Check that all dependencies are properly specified * **Arch Program Version**: Ensure you're using a compatible version * **Build Tools**: Verify Solana CLI is properly installed ### [The validator won't start. What's wrong?](https://book.arch.network/docs/help-resources/faq#the-validator-wont-start-whats-wrong) Common startup issues: * **Docker**: Ensure Docker is running and accessible * **Ports**: Check that required ports (9002, 18443, 8080) are available * **Dependencies**: Verify Bitcoin Core and Titan are properly configured * **Permissions**: Check file permissions for data directories ### [My program deployed but isn't working. How do I debug?](https://book.arch.network/docs/help-resources/faq#my-program-deployed-but-isnt-working-how-do-i-debug) Debugging steps: 1. **Check Logs**: Use `arch-cli orchestrate logs` to view validator logs 2. **Verify Deployment**: Confirm the program was deployed correctly 3. **Test Locally**: Use unit tests to verify program logic 4. **Check Accounts**: Ensure all required accounts are created 5. **Validate Inputs**: Verify instruction data is correct [Community Questions](https://book.arch.network/docs/help-resources/faq#community-questions) --------------------------------------------------------------------------------------------- ### [Where can I get help?](https://book.arch.network/docs/help-resources/faq#where-can-i-get-help) You can get help from: * **Discord**: Join our [Discord community](https://discord.gg/archnetwork) * **GitHub**: Check issues and discussions on our repositories * **Documentation**: Browse our comprehensive documentation * **Examples**: Study our example programs and guides ### [How can I contribute to Arch Network?](https://book.arch.network/docs/help-resources/faq#how-can-i-contribute-to-arch-network) Ways to contribute: * **Code**: Submit pull requests to our repositories * **Documentation**: Help improve our documentation * **Examples**: Create example programs and tutorials * **Testing**: Help test new features and report bugs * **Community**: Help other developers in Discord ### [Is there a roadmap for future features?](https://book.arch.network/docs/help-resources/faq#is-there-a-roadmap-for-future-features) Yes! Planned features include: * **Additional Programming Languages**: Support for more languages * **Enhanced SDKs**: More comprehensive client libraries * **Cross-Chain Bridges**: Integration with other blockchains * **Privacy Features**: Enhanced privacy-preserving capabilities * **Performance Improvements**: Optimizations for better throughput [Still Have Questions?](https://book.arch.network/docs/help-resources/faq#still-have-questions) ------------------------------------------------------------------------------------------------ [### Join Discord\ \ Get help from the community](https://discord.gg/archnetwork) [### GitHub Issues\ \ Report bugs and request features](https://github.com/Arch-Network/arch-network/issues) [### Documentation\ \ Browse our comprehensive guides](https://book.arch.network/docs) [### Examples\ \ Study example programs](https://github.com/Arch-Network/arch-examples) [Writing Your First Arch Program\ \ A comprehensive guide to creating your first Arch program from scratch with a complete counter example](https://book.arch.network/docs/development/writing-your-first-program) [External Resources\ \ External tools, explorers, and resources for Arch Network development](https://book.arch.network/docs/help-resources/resources) ### On this page [General Questions](https://book.arch.network/docs/help-resources/faq#general-questions) [What is Arch Network?](https://book.arch.network/docs/help-resources/faq#what-is-arch-network) [How is Arch Network different from other blockchain platforms?](https://book.arch.network/docs/help-resources/faq#how-is-arch-network-different-from-other-blockchain-platforms) [What programming languages are supported?](https://book.arch.network/docs/help-resources/faq#what-programming-languages-are-supported) [Development Questions](https://book.arch.network/docs/help-resources/faq#development-questions) [How do I get started with Arch Network development?](https://book.arch.network/docs/help-resources/faq#how-do-i-get-started-with-arch-network-development) [What tools do I need for development?](https://book.arch.network/docs/help-resources/faq#what-tools-do-i-need-for-development) [How do I test my programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-test-my-programs) [Technical Questions](https://book.arch.network/docs/help-resources/faq#technical-questions) [How does Arch Network integrate with Bitcoin?](https://book.arch.network/docs/help-resources/faq#how-does-arch-network-integrate-with-bitcoin) [What is the consensus mechanism?](https://book.arch.network/docs/help-resources/faq#what-is-the-consensus-mechanism) [How do I handle Bitcoin transactions in my programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-handle-bitcoin-transactions-in-my-programs) [Deployment Questions](https://book.arch.network/docs/help-resources/faq#deployment-questions) [How do I deploy my program to the network?](https://book.arch.network/docs/help-resources/faq#how-do-i-deploy-my-program-to-the-network) [What networks are available?](https://book.arch.network/docs/help-resources/faq#what-networks-are-available) [How do I interact with deployed programs?](https://book.arch.network/docs/help-resources/faq#how-do-i-interact-with-deployed-programs) [Troubleshooting Questions](https://book.arch.network/docs/help-resources/faq#troubleshooting-questions) [My program won't compile. What should I check?](https://book.arch.network/docs/help-resources/faq#my-program-wont-compile-what-should-i-check) [The validator won't start. What's wrong?](https://book.arch.network/docs/help-resources/faq#the-validator-wont-start-whats-wrong) [My program deployed but isn't working. How do I debug?](https://book.arch.network/docs/help-resources/faq#my-program-deployed-but-isnt-working-how-do-i-debug) [Community Questions](https://book.arch.network/docs/help-resources/faq#community-questions) [Where can I get help?](https://book.arch.network/docs/help-resources/faq#where-can-i-get-help) [How can I contribute to Arch Network?](https://book.arch.network/docs/help-resources/faq#how-can-i-contribute-to-arch-network) [Is there a roadmap for future features?](https://book.arch.network/docs/help-resources/faq#is-there-a-roadmap-for-future-features) [Still Have Questions?](https://book.arch.network/docs/help-resources/faq#still-have-questions) --- # How to Write an Oracle Program Development How to Write an Oracle Program ============================== Complete guide to building oracle programs that provide external data to other programs on Arch Network This guide walks through the inner workings of an oracle program as well as details how oracle data can be utilized by other programs on Arch Network. [Table of Contents](https://book.arch.network/docs/development/how-to-write-oracle-program#table-of-contents) -------------------------------------------------------------------------------------------------------------- * [Description](https://book.arch.network/docs/development/how-to-write-oracle-program#description) * [Flow](https://book.arch.network/docs/development/how-to-write-oracle-program#flow) * [Logic](https://book.arch.network/docs/development/how-to-write-oracle-program#logic) * [Implementation](https://book.arch.network/docs/development/how-to-write-oracle-program#implementation) [Description](https://book.arch.network/docs/development/how-to-write-oracle-program#description) -------------------------------------------------------------------------------------------------- Two important aspects of understanding how this oracle example is implemented within Arch: 1. **The oracle is a program that updates an account which holds the data** 2. **No cross-program invocation occurs** since only the account is updated and read from versus this being another program that gets interacted with from another program The source code can be found within the [arch-examples](https://github.com/Arch-Network/arch-examples) repo. [Flow](https://book.arch.network/docs/development/how-to-write-oracle-program#flow) ------------------------------------------------------------------------------------ The oracle workflow follows these steps: 1. **Project deploys oracle program** 2. **Project creates state account** that the oracle program will control in order to write state to it 3. **Projects submit data to the oracle state account** by submitting instructions to the oracle program 4. **Programs include oracle state account** alongside their program instructions in order to use this referenced data stored in the oracle state account within their program 5. **Projects submit instructions to oracle program periodically** to update oracle state account with fresh data [Logic](https://book.arch.network/docs/development/how-to-write-oracle-program#logic) -------------------------------------------------------------------------------------- If you haven't already read [How to write an Arch program](https://book.arch.network/docs/development/writing-your-first-program) , we recommend starting there to get a basic understanding of the program anatomy before going further. We'll look closely at the logic block contained within the `update_data` handler. pub fn update_data( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let oracle_account = next_account_info(account_iter)?; assert!(oracle_account.is_signer); assert_eq!(instruction_data.len(), 8); // ... rest of implementation } First, we'll iterate over the accounts that get passed into the function, which includes the newly created state account that will be responsible for managing the oracle's data. We then assert that the oracle state account has the appropriate authority to be written to and update what it stores within its data field. Additionally, we assert that the data we wish to update the account with is at least a certain number of bytes. let data_len = oracle_account.data.try_borrow().unwrap().len(); if instruction_data.len() > data_len { oracle_account.realloc(instruction_data.len(), true)?; } Next, we calculate the length of the new data that we are looking to store in the account and reallocate memory to the account if the new data is larger than the data currently existing within the account. This step is important for ensuring that there is no remaining, stale data stored in the account before adding new data to it. oracle_account .data .try_borrow_mut() .unwrap() .copy_from_slice(instruction_data); msg!("updated"); Ok(()) Lastly, we store the new data that is passed into the program via the instruction to the state account for management, thus marking the end of the oracle update process. [Implementation](https://book.arch.network/docs/development/how-to-write-oracle-program#implementation) -------------------------------------------------------------------------------------------------------- Let's look at an example implementation of this oracle program. This includes: * [Create oracle project](https://book.arch.network/docs/development/how-to-write-oracle-program#create-oracle-project) * [Deploy program](https://book.arch.network/docs/development/how-to-write-oracle-program#deploy-program) * [Create a state account](https://book.arch.network/docs/development/how-to-write-oracle-program#create-a-state-account) * [Update the state account](https://book.arch.network/docs/development/how-to-write-oracle-program#update-the-state-account) * [Read from the state account](https://book.arch.network/docs/development/how-to-write-oracle-program#read-from-the-state-account) ### [Create Oracle Project](https://book.arch.network/docs/development/how-to-write-oracle-program#create-oracle-project) First, we'll need to create a new project to hold our oracle logic. # Create a new directory for your oracle project mkdir oracle cd oracle # Initialize a Rust project cargo init --lib The new CLI does not currently have a project creation command. We'll manually set up our project structure. You'll need to create and edit the following files: * `Cargo.toml` - Add dependencies for your oracle program * `src/lib.rs` - Implement the oracle program logic Example program files can be found in the [arch-examples](https://github.com/Arch-Network/arch-examples) repo. #### [Cargo.toml](https://book.arch.network/docs/development/how-to-write-oracle-program#cargotoml) [package] name = "oracle" version = "0.1.0" edition = "2021" [dependencies] arch-program = "0.1.0" borsh = "1.0" #### [src/lib.rs](https://book.arch.network/docs/development/how-to-write-oracle-program#srclibrs) use arch_program::{ account::AccountInfo, entrypoint, msg, program_error::ProgramError, pubkey::Pubkey, borsh::{BorshDeserialize, BorshSerialize}, }; // Define the program's entry point entrypoint!(process_instruction); pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { // Parse the instruction data let instruction = OracleInstruction::try_from_slice(instruction_data)?; match instruction { OracleInstruction::UpdateData { data } => { update_data(program_id, accounts, &data) } } } #[derive(BorshSerialize, BorshDeserialize)] pub enum OracleInstruction { UpdateData { data: Vec }, } pub fn update_data( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let oracle_account = next_account_info(account_iter)?; // Verify the account is owned by this program if oracle_account.owner != program_id { return Err(ProgramError::IncorrectProgramId); } // Verify the account is a signer (has authority to update) if !oracle_account.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Ensure we have data to store if instruction_data.is_empty() { return Err(ProgramError::InvalidInstructionData); } // Reallocate memory if needed let data_len = oracle_account.data.try_borrow().unwrap().len(); if instruction_data.len() > data_len { oracle_account.realloc(instruction_data.len(), true)?; } // Update the account data oracle_account .data .try_borrow_mut() .unwrap() .copy_from_slice(instruction_data); msg!("Oracle data updated successfully"); Ok(()) } ### [Deploy Program](https://book.arch.network/docs/development/how-to-write-oracle-program#deploy-program) Once you have your oracle program written, you can deploy it to the Arch Network: # Build the program cargo build-sbf # Deploy the program arch-cli program deploy target/deploy/oracle.so ### [Create a State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#create-a-state-account) After deploying your oracle program, you need to create a state account that will hold the oracle data: # Create a new account for storing oracle data arch-cli account create \ --keypair-path ~/oracle_state.key \ --space 1024 \ --owner \ --keypair-path ~/payer.key ### [Update the State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#update-the-state-account) Now you can update the oracle data by calling your program: # Update oracle data with new information arch-cli program call \ --accounts ~/oracle_state.key \ --instruction-data \ --keypair-path ~/oracle_authority.key ### [Read from the State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#read-from-the-state-account) Other programs can read the oracle data by including the state account in their instruction: // In your consumer program pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let oracle_account = next_account_info(account_iter)?; // Read the oracle data let oracle_data = oracle_account.data.try_borrow().unwrap(); // Process the oracle data // ... your logic here Ok(()) } [Advanced Oracle Patterns](https://book.arch.network/docs/development/how-to-write-oracle-program#advanced-oracle-patterns) ---------------------------------------------------------------------------------------------------------------------------- ### [Price Oracle Example](https://book.arch.network/docs/development/how-to-write-oracle-program#price-oracle-example) Here's a more sophisticated example of a price oracle that stores structured data: use arch_program::{ account::AccountInfo, entrypoint, msg, program_error::ProgramError, pubkey::Pubkey, borsh::{BorshDeserialize, BorshSerialize}, }; #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct PriceData { pub price: u64, // Price in smallest unit (e.g., satoshis) pub decimals: u8, // Number of decimal places pub timestamp: i64, // Unix timestamp pub source: String, // Data source identifier } #[derive(BorshSerialize, BorshDeserialize)] pub enum PriceOracleInstruction { UpdatePrice { price_data: PriceData }, GetPrice, } pub fn update_price( program_id: &Pubkey, accounts: &[AccountInfo], price_data: PriceData, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let oracle_account = next_account_info(account_iter)?; // Verify ownership and authority if oracle_account.owner != program_id { return Err(ProgramError::IncorrectProgramId); } if !oracle_account.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Serialize the price data let serialized_data = price_data.try_to_vec() .map_err(|_| ProgramError::InvalidInstructionData)?; // Reallocate if needed let current_len = oracle_account.data.try_borrow().unwrap().len(); if serialized_data.len() > current_len { oracle_account.realloc(serialized_data.len(), true)?; } // Update the account data oracle_account .data .try_borrow_mut() .unwrap() .copy_from_slice(&serialized_data); msg!("Price updated: {} at {}", price_data.price, price_data.timestamp); Ok(()) } ### [Multi-Source Oracle](https://book.arch.network/docs/development/how-to-write-oracle-program#multi-source-oracle) For more robust oracles, you might want to aggregate data from multiple sources: #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct MultiSourcePrice { pub sources: Vec, pub aggregated_price: u64, pub confidence: u8, // 0-100 confidence score } pub fn aggregate_prices(prices: Vec) -> MultiSourcePrice { if prices.is_empty() { return MultiSourcePrice { sources: vec![], aggregated_price: 0, confidence: 0, }; } // Simple average for demonstration let total: u64 = prices.iter().map(|p| p.price).sum(); let average_price = total / prices.len() as u64; // Calculate confidence based on price variance let variance = prices.iter() .map(|p| (p.price as i64 - average_price as i64).pow(2)) .sum::() / prices.len() as i64; let confidence = (100 - (variance as u64 / 1000).min(100)) as u8; MultiSourcePrice { sources: prices, aggregated_price: average_price, confidence, } } [Security Considerations](https://book.arch.network/docs/development/how-to-write-oracle-program#security-considerations) -------------------------------------------------------------------------------------------------------------------------- ### [Access Control](https://book.arch.network/docs/development/how-to-write-oracle-program#access-control) pub fn verify_oracle_authority( oracle_account: &AccountInfo, expected_authority: &Pubkey, ) -> Result<(), ProgramError> { // Check if the account is owned by the oracle program if oracle_account.owner != &ORACLE_PROGRAM_ID { return Err(ProgramError::IncorrectProgramId); } // Verify the authority if oracle_account.key != expected_authority { return Err(ProgramError::InvalidAccountData); } // Ensure the account is a signer if !oracle_account.is_signer { return Err(ProgramError::MissingRequiredSignature); } Ok(()) } ### [Data Validation](https://book.arch.network/docs/development/how-to-write-oracle-program#data-validation) pub fn validate_price_data(price_data: &PriceData) -> Result<(), ProgramError> { // Check for reasonable price range if price_data.price == 0 { return Err(ProgramError::InvalidInstructionData); } // Check timestamp is recent (within last hour) let current_time = arch_program::clock::Clock::get()?.unix_timestamp; if current_time - price_data.timestamp > 3600 { return Err(ProgramError::InvalidInstructionData); } // Validate decimals if price_data.decimals > 18 { return Err(ProgramError::InvalidInstructionData); } Ok(()) } [Testing Your Oracle](https://book.arch.network/docs/development/how-to-write-oracle-program#testing-your-oracle) ------------------------------------------------------------------------------------------------------------------ ### [Unit Tests](https://book.arch.network/docs/development/how-to-write-oracle-program#unit-tests) #[cfg(test)] mod tests { use super::*; use arch_program::test_utils::*; #[test] fn test_price_update() { let program_id = Pubkey::new_unique(); let oracle_account = create_test_account(&program_id, 1024); let price_data = PriceData { price: 50000, decimals: 8, timestamp: 1640995200, source: "coinbase".to_string(), }; let result = update_price( &program_id, &[oracle_account], price_data, ); assert!(result.is_ok()); } } ### [Integration Tests](https://book.arch.network/docs/development/how-to-write-oracle-program#integration-tests) # Test oracle update arch-cli program call \ --accounts ~/oracle_state.key \ --instruction-data $(echo '{"price": 50000, "decimals": 8, "timestamp": 1640995200, "source": "coinbase"}' | base64) \ --keypair-path ~/oracle_authority.key # Verify the update arch-cli account show ~/oracle_state.key [Best Practices](https://book.arch.network/docs/development/how-to-write-oracle-program#best-practices) -------------------------------------------------------------------------------------------------------- ### [1\. Data Freshness](https://book.arch.network/docs/development/how-to-write-oracle-program#1-data-freshness) * Implement timestamp validation to ensure data is recent * Set appropriate expiration times for oracle data * Consider implementing staleness penalties ### [2\. Source Diversity](https://book.arch.network/docs/development/how-to-write-oracle-program#2-source-diversity) * Aggregate data from multiple sources when possible * Implement confidence scoring based on source agreement * Weight sources based on their historical accuracy ### [3\. Security](https://book.arch.network/docs/development/how-to-write-oracle-program#3-security) * Use proper access controls for oracle updates * Implement rate limiting to prevent spam updates * Consider using multisig for critical oracle operations ### [4\. Efficiency](https://book.arch.network/docs/development/how-to-write-oracle-program#4-efficiency) * Optimize data structures for minimal storage costs * Use appropriate data types to reduce serialization overhead * Consider compression for large datasets [Next Steps](https://book.arch.network/docs/development/how-to-write-oracle-program#next-steps) ------------------------------------------------------------------------------------------------ [### Runes Swap Guide\ \ Learn to build a token swap protocol](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap) [### Lending Protocol\ \ Create a lending protocol using oracles](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol) [### Program Development\ \ Master Arch program development](https://book.arch.network/docs/development/writing-your-first-program) [### Arch Examples\ \ Explore more example programs](https://github.com/Arch-Network/arch-examples) [Resources](https://book.arch.network/docs/development/how-to-write-oracle-program#resources) ---------------------------------------------------------------------------------------------- [### Arch Examples Repository\ \ Complete oracle implementation examples](https://github.com/Arch-Network/arch-examples) [### Program Development Guide\ \ Learn the basics of Arch program development](https://book.arch.network/docs/development/writing-your-first-program) [### Account Management\ \ Understand account management in Arch programs](https://book.arch.network/docs/development/writing-your-first-program) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [Creating APL Tokens on Arch Network\ \ Complete guide to creating and managing fungible tokens using the APL Token Program](https://book.arch.network/docs/development/how-to-create-a-fungible-token) [Writing Your First Arch Program\ \ A comprehensive guide to creating your first Arch program from scratch with a complete counter example](https://book.arch.network/docs/development/writing-your-first-program) ### On this page [Table of Contents](https://book.arch.network/docs/development/how-to-write-oracle-program#table-of-contents) [Description](https://book.arch.network/docs/development/how-to-write-oracle-program#description) [Flow](https://book.arch.network/docs/development/how-to-write-oracle-program#flow) [Logic](https://book.arch.network/docs/development/how-to-write-oracle-program#logic) [Implementation](https://book.arch.network/docs/development/how-to-write-oracle-program#implementation) [Create Oracle Project](https://book.arch.network/docs/development/how-to-write-oracle-program#create-oracle-project) [Cargo.toml](https://book.arch.network/docs/development/how-to-write-oracle-program#cargotoml) [src/lib.rs](https://book.arch.network/docs/development/how-to-write-oracle-program#srclibrs) [Deploy Program](https://book.arch.network/docs/development/how-to-write-oracle-program#deploy-program) [Create a State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#create-a-state-account) [Update the State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#update-the-state-account) [Read from the State Account](https://book.arch.network/docs/development/how-to-write-oracle-program#read-from-the-state-account) [Advanced Oracle Patterns](https://book.arch.network/docs/development/how-to-write-oracle-program#advanced-oracle-patterns) [Price Oracle Example](https://book.arch.network/docs/development/how-to-write-oracle-program#price-oracle-example) [Multi-Source Oracle](https://book.arch.network/docs/development/how-to-write-oracle-program#multi-source-oracle) [Security Considerations](https://book.arch.network/docs/development/how-to-write-oracle-program#security-considerations) [Access Control](https://book.arch.network/docs/development/how-to-write-oracle-program#access-control) [Data Validation](https://book.arch.network/docs/development/how-to-write-oracle-program#data-validation) [Testing Your Oracle](https://book.arch.network/docs/development/how-to-write-oracle-program#testing-your-oracle) [Unit Tests](https://book.arch.network/docs/development/how-to-write-oracle-program#unit-tests) [Integration Tests](https://book.arch.network/docs/development/how-to-write-oracle-program#integration-tests) [Best Practices](https://book.arch.network/docs/development/how-to-write-oracle-program#best-practices) [1\. Data Freshness](https://book.arch.network/docs/development/how-to-write-oracle-program#1-data-freshness) [2\. Source Diversity](https://book.arch.network/docs/development/how-to-write-oracle-program#2-source-diversity) [3\. Security](https://book.arch.network/docs/development/how-to-write-oracle-program#3-security) [4\. Efficiency](https://book.arch.network/docs/development/how-to-write-oracle-program#4-efficiency) [Next Steps](https://book.arch.network/docs/development/how-to-write-oracle-program#next-steps) [Resources](https://book.arch.network/docs/development/how-to-write-oracle-program#resources) --- # Cross-Program Invocation (CPI) Program Cross-Program Invocation (CPI) ============================== Cross-Program Invocation (CPI) lets one Arch program call another program within the same transaction. CPI enables composition, modularity, and reuse of on-chain logic. [When to use CPI](https://book.arch.network/docs/program/cpi#when-to-use-cpi) ------------------------------------------------------------------------------ * Reuse core program logic (e.g., token transfers) * Orchestrate multi-program workflows atomically * Delegate permissions via PDAs instead of exposing private keys [Basic CPI](https://book.arch.network/docs/program/cpi#basic-cpi) ------------------------------------------------------------------ use arch_program::{ account_info::AccountInfo, instruction::{AccountMeta, Instruction}, program::invoke, pubkey::Pubkey, }; pub fn transfer_tokens_cpi( token_program_id: &Pubkey, source: &AccountInfo, destination: &AccountInfo, authority: &AccountInfo, amount: u64, ) -> arch_program::entrypoint::ProgramResult { let accounts = vec![\ AccountMeta::new(*source.key, false),\ AccountMeta::new(*destination.key, false),\ AccountMeta::new_readonly(*authority.key, true),\ ]; // Your program's instruction layout here let instruction = Instruction::new_with_bytes( *token_program_id, &amount.to_le_bytes(), accounts, ); invoke(&instruction, &[source.clone(), destination.clone(), authority.clone()]) } [CPI with Program-Derived Address (PDA)](https://book.arch.network/docs/program/cpi#cpi-with-program-derived-address-pda) -------------------------------------------------------------------------------------------------------------------------- Use `invoke_signed` when the "authority" is a PDA owned by your program. use arch_program::{ account_info::AccountInfo, program::invoke_signed, pubkey::Pubkey, system_instruction, }; pub fn transfer_from_pda( program_id: &Pubkey, pda_account: &AccountInfo, recipient: &AccountInfo, lamports: u64, seeds: &[&[u8]], ) -> arch_program::entrypoint::ProgramResult { let ix = system_instruction::transfer(pda_account.key, recipient.key, lamports); // PDA must be the signer via seeds invoke_signed( &ix, &[pda_account.clone(), recipient.clone()], &[seeds], ) } ### [Deriving PDAs](https://book.arch.network/docs/program/cpi#deriving-pdas) use arch_program::pubkey::Pubkey; pub fn user_pda(user: &Pubkey, program_id: &Pubkey) -> (Pubkey, u8) { Pubkey::find_program_address(&[b"user", user.as_ref()], program_id) } [Common Patterns](https://book.arch.network/docs/program/cpi#common-patterns) ------------------------------------------------------------------------------ ### [Initialize + Use Flow](https://book.arch.network/docs/program/cpi#initialize--use-flow) use arch_program::{ account_info::{next_account_info, AccountInfo}, instruction::{AccountMeta, Instruction}, program::{invoke, invoke_signed}, pubkey::Pubkey, entrypoint::ProgramResult, }; pub fn process_initialize( program_id: &Pubkey, accounts: &[AccountInfo], ) -> ProgramResult { let accounts_iter = &mut accounts.iter(); let payer = next_account_info(accounts_iter)?; let pda_account = next_account_info(accounts_iter)?; let system_program = next_account_info(accounts_iter)?; // Derive PDA let (pda, bump) = Pubkey::find_program_address(&[b"vault"], program_id); if pda != *pda_account.key { return Err(arch_program::program_error::ProgramError::InvalidSeeds); } // Create PDA account via CPI to system program let rent = arch_program::sysvar::rent::Rent::get()?; let lamports = rent.minimum_balance(0); let create_ix = arch_program::system_instruction::create_account( payer.key, &pda, lamports, 0, program_id, ); invoke_signed( &create_ix, &[payer.clone(), pda_account.clone(), system_program.clone()], &[&[b"vault", &[bump]]], ) } ### [Chaining Calls](https://book.arch.network/docs/program/cpi#chaining-calls) You can call multiple programs in sequence within a single transaction. If any CPI fails, the entire transaction aborts. [Client-Side Considerations](https://book.arch.network/docs/program/cpi#client-side-considerations) ---------------------------------------------------------------------------------------------------- * Build messages so that all required program accounts and PDAs are present * Ensure PDA bumps and seeds are reproduced client-side for address derivation * Keep instruction data small; respect transaction size limits // TypeScript helper to derive the same PDA as on-chain import { PublicKey } from '@solana/web3.js'; // replace with Arch TS when available export function deriveVaultPda(programId: PublicKey) { return PublicKey.findProgramAddressSync([Buffer.from('vault')], programId); } [Security Best Practices](https://book.arch.network/docs/program/cpi#security-best-practices) ---------------------------------------------------------------------------------------------- * Verify account ownership: check that accounts are owned by expected programs * Validate signer/writable flags for all accounts used in CPI * Never trust instruction data from clients; validate thoroughly * Use PDAs to avoid holding private keys on-chain [Troubleshooting](https://book.arch.network/docs/program/cpi#troubleshooting) ------------------------------------------------------------------------------ * InvalidSeeds: PDA mismatch between client and program (check seeds/bump) * MissingRequiredSignature: Caller did not provide required signer * IncorrectProgramId: Account not owned by expected program * Size/limit errors: Split flows into multiple transactions if needed [Account Guide\ \ Previous Page](https://book.arch.network/docs/program/accounts) [Entrypoint and Handler Functions\ \ Next Page](https://book.arch.network/docs/program/entrypoint) ### On this page [When to use CPI](https://book.arch.network/docs/program/cpi#when-to-use-cpi) [Basic CPI](https://book.arch.network/docs/program/cpi#basic-cpi) [CPI with Program-Derived Address (PDA)](https://book.arch.network/docs/program/cpi#cpi-with-program-derived-address-pda) [Deriving PDAs](https://book.arch.network/docs/program/cpi#deriving-pdas) [Common Patterns](https://book.arch.network/docs/program/cpi#common-patterns) [Initialize + Use Flow](https://book.arch.network/docs/program/cpi#initialize--use-flow) [Chaining Calls](https://book.arch.network/docs/program/cpi#chaining-calls) [Client-Side Considerations](https://book.arch.network/docs/program/cpi#client-side-considerations) [Security Best Practices](https://book.arch.network/docs/program/cpi#security-best-practices) [Troubleshooting](https://book.arch.network/docs/program/cpi#troubleshooting) --- # Instructions and Messages Program Instructions and Messages ========================= Instructions and messages are fundamental components of Arch's transaction processing system that enable communication between clients and [programs](https://book.arch.network/docs/program/program) . They form the basis for all state changes and interactions within the Arch network. ### [Instructions](https://book.arch.network/docs/program/instructions-and-messages#instructions) An instruction is the basic unit of program execution in Arch. It contains all the information needed for a [program](https://book.arch.network/docs/program/program) to execute a specific operation. Instructions are processed atomically, meaning they either complete entirely or have no effect. #### [Structure](https://book.arch.network/docs/program/instructions-and-messages#structure) pub struct Instruction { /// Program ID that executes this instruction pub program_id: Pubkey, /// Accounts required for this instruction pub accounts: Vec, /// Instruction data pub data: Vec, } #### [Components:](https://book.arch.network/docs/program/instructions-and-messages#components) 1. **Program ID**: The [pubkey](https://book.arch.network/docs/sdk/pubkey.md) of the [program](https://book.arch.network/docs/program/program) that will process the instruction 2. **Accounts**: List of accounts required for the instruction, with their metadata 3. **Instruction Data**: Custom data specific to the instruction, typically serialized using Borsh or another format #### [Account Metadata](https://book.arch.network/docs/program/instructions-and-messages#account-metadata) pub struct AccountMeta { pub pubkey: Pubkey, pub is_signer: bool, pub is_writable: bool, } * `pubkey`: The account's public key * `is_signer`: Whether the account must sign the transaction * `is_writable`: Whether the account's data can be modified ### [Messages](https://book.arch.network/docs/program/instructions-and-messages#messages) A message is a collection of instructions that form a [transaction](https://book.arch.network/docs/sdk/runtime-transaction.md) . Messages ensure atomic execution of multiple instructions, meaning either all instructions succeed or none take effect. #### [Structure](https://book.arch.network/docs/program/instructions-and-messages#structure-1) pub struct Message { /// List of account keys referenced by the instructions pub account_keys: Vec, /// Recent blockhash pub recent_blockhash: Hash, /// List of instructions to execute pub instructions: Vec, } #### [Components:](https://book.arch.network/docs/program/instructions-and-messages#components-1) 1. **Account Keys**: All unique accounts referenced across instructions 2. **Recent Blockhash**: Used for transaction uniqueness and timeout 3. **Instructions**: List of instructions to execute in sequence ### [Instruction Processing Flow:](https://book.arch.network/docs/program/instructions-and-messages#instruction-processing-flow) 1. Client creates an instruction with: * [Program](https://book.arch.network/docs/program/program) ID to execute the instruction * Required accounts with appropriate permissions * Instruction-specific data (serialized parameters) 2. Instruction(s) are bundled into a message: * Multiple instructions can be atomic * Account permissions are consolidated * Blockhash is included for uniqueness 3. Message is signed to create a [transaction](https://book.arch.network/docs/sdk/runtime-transaction.md) : * All required signers must sign * Transaction size limits apply * Fees are calculated 4. Transaction is sent to the network: * Validated by validators * Processed in parallel when possible * Results are confirmed 5. Program processes the instruction: * Deserializes instruction data * Validates accounts and permissions * Executes operation * Updates account state ### [Best Practices:](https://book.arch.network/docs/program/instructions-and-messages#best-practices) 1. **Account Validation** * Always verify account ownership * Check account permissions * Validate account relationships 2. **Data Serialization** * Use consistent serialization format (preferably Borsh) * Include version information * Handle errors gracefully * Validate data lengths 3. **Error Handling** * Return specific error types * Provide clear error messages * Handle all edge cases * Implement proper cleanup ### [Cross-Program Invocation (CPI)](https://book.arch.network/docs/program/instructions-and-messages#cross-program-invocation-cpi) Instructions can invoke other [programs](https://book.arch.network/docs/program/program) through CPI, enabling composability: 1. Create new instruction for target program: * Specify program ID * Include required accounts * Prepare instruction data 2. Pass required accounts: * Include all necessary accounts * Set proper permissions * Handle PDA derivation 3. Invoke using `invoke` or `invoke_signed`: * For regular accounts: `invoke` * For PDAs: `invoke_signed` * Handle return values 4. Handle results: * Check return status * Process any returned data * Handle errors appropriately ### [Security Considerations:](https://book.arch.network/docs/program/instructions-and-messages#security-considerations) 1. **Account Verification** * Verify all account permissions * Check ownership and signatures * Validate account relationships * Prevent privilege escalation 2. **Data Validation** * Sanitize all input data * Check buffer lengths * Validate numerical ranges * Prevent integer overflow 3. **State Management** * Maintain atomic operations * Handle partial failures * Prevent race conditions * Ensure consistent state ### [Common Patterns:](https://book.arch.network/docs/program/instructions-and-messages#common-patterns) 1. **Initialization** * Create necessary accounts * Set initial state * Assign proper ownership 2. **State Updates** * Validate permissions * Update account data * Maintain invariants 3. **Account Management** * Close accounts when done * Manage PDAs properly [Entrypoint and Handler Functions\ \ Previous Page](https://book.arch.network/docs/program/entrypoint) [Program\ \ Next Page](https://book.arch.network/docs/program/program) ### On this page [Instructions](https://book.arch.network/docs/program/instructions-and-messages#instructions) [Structure](https://book.arch.network/docs/program/instructions-and-messages#structure) [Components:](https://book.arch.network/docs/program/instructions-and-messages#components) [Account Metadata](https://book.arch.network/docs/program/instructions-and-messages#account-metadata) [Messages](https://book.arch.network/docs/program/instructions-and-messages#messages) [Structure](https://book.arch.network/docs/program/instructions-and-messages#structure-1) [Components:](https://book.arch.network/docs/program/instructions-and-messages#components-1) [Instruction Processing Flow:](https://book.arch.network/docs/program/instructions-and-messages#instruction-processing-flow) [Best Practices:](https://book.arch.network/docs/program/instructions-and-messages#best-practices) [Cross-Program Invocation (CPI)](https://book.arch.network/docs/program/instructions-and-messages#cross-program-invocation-cpi) [Security Considerations:](https://book.arch.network/docs/program/instructions-and-messages#security-considerations) [Common Patterns:](https://book.arch.network/docs/program/instructions-and-messages#common-patterns) --- # Entrypoint and Handler Functions Program Entrypoint and Handler Functions ================================ [Entrypoint](https://book.arch.network/docs/program/entrypoint#entrypoint) --------------------------------------------------------------------------- Every Arch program includes a single entrypoint used to invoke the program. A [handler function](https://book.arch.network/docs/program/entrypoint#handler-function) is then used to process the data passed into the entrypoint. entrypoint!(process_instruction); [lib.rs](https://github.com/Arch-Network/arch-examples/blob/main/examples/helloworld/program/src/lib.rs) #### [Initialization and Data Reading:](https://book.arch.network/docs/program/entrypoint#initialization-and-data-reading) The entrypoint begins by initializing and reading serialized data that is passed in, which includes everything needed for program execution. It then deserializes this data to obtain the [instruction](https://book.arch.network/docs/program/instructions-and-messages) , an object which contains all necessary details like the `program_id` and associated [UTXO](https://book.arch.network/docs/program/utxo.md) information. It passes in all deserialized data in to the [handler function](https://book.arch.network/docs/program/entrypoint#handler-function) for processing of the [program](https://book.arch.network/docs/program/program) 's business logic; this could involve transactions, state updates, or other program-specific operations. [Handler function](https://book.arch.network/docs/program/entrypoint#handler-function) --------------------------------------------------------------------------------------- Here we'll discuss the dispatcher function, in our case, named: `process_instruction`. This dispatcher function requires the following parameters: * `program_id` - Unique identifier of the currently executing program. * `accounts` - Slice reference containing accounts needed to execute an instruction. * `instruction_data` - Serialized data containing program instructions. This returns a [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) representing success (`Ok`) or failture ([`ProgramError`](https://github.com/Arch-Network/arch-examples/blob/main/program/src/program_error.rs) ). pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { ... } [lib.rs](https://github.com/Arch-Network/arch-examples/blob/main/examples/helloworld/program/src/lib.rs) This function is responsible for parsing and directing the execution flow based on the type of transaction or method specified. It is a critical component that developers must implement to ensure that their programs can appropriately respond to different operational requests. The handler function is defined as part of the program and is facilitated via the [`entrypoint!`](https://book.arch.network/docs/program/entrypoint#entrypoint) . This macro binds the `process_instruction` function to be the first receiver of any execution call made by the Arch virtual machine, effectively making it the gatekeeper for all incoming instructions. #### [Deserialize Input Data](https://book.arch.network/docs/program/entrypoint#deserialize-input-data) The function starts by deserializing the input data (`instruction_data`) into a known format, typically a custom struct that represents different methods or commands the program can execute. #### [Method Dispatch](https://book.arch.network/docs/program/entrypoint#method-dispatch) Based on the deserialized data, the function determines which specific method to execute. This is often handled through a match statement that routes to different functions or modules within the program. #### [Execute Business Logic](https://book.arch.network/docs/program/entrypoint#execute-business-logic) Each routed function performs specific business logic related to the program's purpose, such as managing assets, updating state, or interacting with other program or tokens. #### [Result Commitment:](https://book.arch.network/docs/program/entrypoint#result-commitment) Upon successful execution, the new UTXO authorities, new UTXO Data and a Bitcoin transaction are committed back to the network. [Cross-Program Invocation (CPI)\ \ Previous Page](https://book.arch.network/docs/program/cpi) [Instructions and Messages\ \ Next Page](https://book.arch.network/docs/program/instructions-and-messages) ### On this page [Entrypoint](https://book.arch.network/docs/program/entrypoint#entrypoint) [Initialization and Data Reading:](https://book.arch.network/docs/program/entrypoint#initialization-and-data-reading) [Handler function](https://book.arch.network/docs/program/entrypoint#handler-function) [Deserialize Input Data](https://book.arch.network/docs/program/entrypoint#deserialize-input-data) [Method Dispatch](https://book.arch.network/docs/program/entrypoint#method-dispatch) [Execute Business Logic](https://book.arch.network/docs/program/entrypoint#execute-business-logic) [Result Commitment:](https://book.arch.network/docs/program/entrypoint#result-commitment) --- # Account Guide Program Account Guide ============= > For the core account structure and data types, see [Account Structure](https://book.arch.network/docs/sdk/account.md) > . Accounts are the fundamental building blocks for state management and program interaction in Arch Network. They serve as containers for both program code and state data, bridging the gap between Bitcoin's UTXO model and modern programmable state machines. > For detailed documentation on core system functions used to interact with accounts (like `invoke`, `new_create_account_instruction`, `add_state_transition`, and `set_transaction_to_sign`), see [System Functions](https://book.arch.network/docs/program/system-functions.md) > . [Core Concepts](https://book.arch.network/docs/program/accounts#core-concepts) ------------------------------------------------------------------------------- ### [Account Fundamentals](https://book.arch.network/docs/program/accounts#account-fundamentals) Every account in Arch Network is uniquely identified by a public key (pubkey) and contains four essential components: pub struct Account { /// The program that owns this account pub owner: Pubkey, /// Number of lamports assigned to this account pub lamports: u64, /// Data held in this account pub data: Vec, /// Whether this account can process instructions pub executable: bool, } #### [Component Details:](https://book.arch.network/docs/program/accounts#component-details) 1. **Owner (Pubkey)** * Controls account modifications * Determines which program can modify data * Can be transferred to new programs * Required for all accounts 2. **Lamports (u64)** * Native token balance * Used for: * Transaction fees * Rent payments * State storage costs * Program execution fees 3. **Data (Vec)** * Flexible byte array for state storage * Common uses: * Program code (if executable) * Program state * UTXO metadata * Configuration data * Size determined at creation 4. **Executable Flag (bool)** * Determines if account contains program code * Immutable after deployment * Controls instruction processing capability [Account Types & Use Cases](https://book.arch.network/docs/program/accounts#account-types--use-cases) ------------------------------------------------------------------------------------------------------ ### [1\. Program Accounts](https://book.arch.network/docs/program/accounts#1-program-accounts) Program accounts contain executable code and form the backbone of Arch Network's programmable functionality. // Example program account creation let program_account = SystemInstruction::CreateAccount { lamports: rent.minimum_balance(program_data.len()), space: program_data.len() as u64, owner: bpf_loader::id(), // BPF Loader owns program accounts executable: true, data: program_data, }; Key characteristics: * Immutable after deployment * Owned by BPF loader * Contains verified program code * Processes instructions ### [2\. Data Accounts](https://book.arch.network/docs/program/accounts#2-data-accounts) Data accounts store program state and user data. They're highly flexible and can be structured to meet various needs. // Example data structure for a game account #[derive(BorshSerialize, BorshDeserialize)] pub struct GameAccount { pub player: Pubkey, pub score: u64, pub level: u8, pub achievements: Vec, pub last_played: i64, } // Creating a data account let game_account = SystemInstruction::CreateAccount { lamports: rent.minimum_balance(size_of::()), space: size_of::() as u64, owner: game_program::id(), executable: false, data: Vec::new(), // Will be initialized by program }; Common use cases: * Player profiles * Game state * DeFi positions * NFT metadata * Configuration settings ### [3\. UTXO Accounts](https://book.arch.network/docs/program/accounts#3-utxo-accounts) Special data accounts that bridge Bitcoin UTXOs with Arch Network state. #[derive(BorshSerialize, BorshDeserialize)] pub struct UtxoAccount { pub meta: UtxoMeta, pub owner: Pubkey, pub delegate: Option, pub state: UtxoState, pub created_at: i64, pub last_updated: i64, pub constraints: Vec, } // Example UTXO account creation let utxo_account = SystemInstruction::CreateAccount { lamports: rent.minimum_balance(size_of::()), space: size_of::() as u64, owner: utxo_program::id(), executable: false, data: Vec::new(), }; [Account Interactions](https://book.arch.network/docs/program/accounts#account-interactions) --------------------------------------------------------------------------------------------- Account interactions in Arch Network are facilitated through a set of core system functions. These functions handle everything from account creation to state transitions and are documented in detail in [System Functions](https://book.arch.network/docs/program/system-functions.md) . Below are common patterns for account interactions: ### [1\. Creation Patterns](https://book.arch.network/docs/program/accounts#1-creation-patterns) // 1. Basic account creation pub fn create_basic_account( payer: &Keypair, space: u64, owner: &Pubkey, ) -> Result { let account = Keypair::new(); let rent = banks_client.get_rent().await?; let lamports = rent.minimum_balance(space as usize); let ix = system_instruction::create_account( &payer.pubkey(), &account.pubkey(), lamports, space, owner, ); let tx = Transaction::new_signed_with_payer( &[ix], Some(&payer.pubkey()), &[payer, &account], recent_blockhash, ); banks_client.process_transaction(tx).await?; Ok(account) } // 2. PDA (Program Derived Address) creation pub fn create_pda_account( program_id: &Pubkey, seeds: &[&[u8]], space: u64, ) -> Result { let (pda, bump) = Pubkey::find_program_address(seeds, program_id); let ix = system_instruction::create_account( &payer.pubkey(), &pda, lamports, space, program_id, ); // Include the bump seed for deterministic address let seeds_with_bump = &[&seeds[..], &[&[bump]]].concat(); let signer_seeds = &[&seeds_with_bump[..]]; invoke_signed(&ix, &[payer, pda], signer_seeds)?; Ok(pda) } ### [2\. State Management](https://book.arch.network/docs/program/accounts#2-state-management) // Example of managing account state pub trait AccountState: Sized { fn try_from_slice(data: &[u8]) -> Result; fn try_serialize(&self) -> Result, Error>; fn load(account: &AccountInfo) -> Result { Self::try_from_slice(&account.data.borrow()) } fn save(&self, account: &AccountInfo) -> Result<(), Error> { let data = self.try_serialize()?; let mut account_data = account.data.borrow_mut(); account_data[..data.len()].copy_from_slice(&data); Ok(()) } } // Implementation example impl AccountState for GameAccount { fn update_score(&mut self, new_score: u64) -> Result<(), Error> { self.score = new_score; self.last_played = Clock::get()?.unix_timestamp; Ok(()) } } ### [3\. Cross-Program Invocation (CPI)](https://book.arch.network/docs/program/accounts#3-cross-program-invocation-cpi) // Example of one program calling another pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> ProgramResult { // Deserialize accounts let account_info_iter = &mut accounts.iter(); let source_info = next_account_info(account_info_iter)?; let dest_info = next_account_info(account_info_iter)?; let system_program = next_account_info(account_info_iter)?; // Create CPI context let cpi_accounts = Transfer { from: source_info.clone(), to: dest_info.clone(), }; let cpi_program = system_program.clone(); let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts); // Perform cross-program invocation transfer(cpi_ctx, amount)?; Ok(()) } [Security Considerations](https://book.arch.network/docs/program/accounts#security-considerations) --------------------------------------------------------------------------------------------------- ### [1\. Access Control](https://book.arch.network/docs/program/accounts#1-access-control) fn verify_account_access( account: &AccountInfo, expected_owner: &Pubkey, writable: bool, ) -> ProgramResult { // Check account ownership if account.owner != expected_owner { return Err(ProgramError::IncorrectProgramId); } // Verify write permission if needed if writable && !account.is_writable { return Err(ProgramError::InvalidAccountData); } // Additional checks... Ok(()) } ### [2\. Data Validation](https://book.arch.network/docs/program/accounts#2-data-validation) fn validate_account_data( account: &AccountInfo, validate_fn: impl Fn(&T) -> bool, ) -> ProgramResult { // Load and validate account data let data = T::load(account)?; if !validate_fn(&data) { return Err(ProgramError::InvalidAccountData); } Ok(()) } [Best Practices](https://book.arch.network/docs/program/accounts#best-practices) --------------------------------------------------------------------------------- ### [1\. Account Management](https://book.arch.network/docs/program/accounts#1-account-management) * Always validate account ownership before modifications * Use PDAs for deterministic addresses * Implement proper error handling * Close unused accounts to reclaim rent ### [2\. Data Safety](https://book.arch.network/docs/program/accounts#2-data-safety) * Validate all input data * Use proper serialization * Handle account size limits * Implement atomic operations ### [3\. Performance](https://book.arch.network/docs/program/accounts#3-performance) * Minimize account creations * Batch operations when possible * Use appropriate data structures * Cache frequently accessed data ### [4\. Upgrades](https://book.arch.network/docs/program/accounts#4-upgrades) * Plan for version management * Implement migration strategies * Use flexible data structures * Document state changes [Common Patterns](https://book.arch.network/docs/program/accounts#common-patterns) ----------------------------------------------------------------------------------- ### [1\. Account Initialization](https://book.arch.network/docs/program/accounts#1-account-initialization) pub fn initialize_account( program_id: &Pubkey, account: &AccountInfo, initial_state: T, ) -> ProgramResult { // Verify account is uninitialized if !account.data_is_empty() { return Err(ProgramError::AccountAlreadyInitialized); } // Set account owner account.set_owner(program_id)?; // Initialize state initial_state.save(account)?; Ok(()) } ### [2\. Account Updates](https://book.arch.network/docs/program/accounts#2-account-updates) pub fn update_account( account: &AccountInfo, update_fn: impl FnOnce(&mut T) -> ProgramResult, ) -> ProgramResult { // Load current state let mut state = T::load(account)?; // Apply update update_fn(&mut state)?; // Save updated state state.save(account)?; Ok(()) } ### [3\. Account Closure](https://book.arch.network/docs/program/accounts#3-account-closure) pub fn close_account( account: &AccountInfo, destination: &AccountInfo, ) -> ProgramResult { // Transfer lamports let dest_starting_lamports = destination.lamports(); **destination.lamports.borrow_mut() = dest_starting_lamports .checked_add(account.lamports()) .ok_or(ProgramError::Overflow)?; **account.lamports.borrow_mut() = 0; // Clear data account.data.borrow_mut().fill(0); Ok(()) } [Related Topics](https://book.arch.network/docs/program/accounts#related-topics) --------------------------------------------------------------------------------- * [UTXOs](https://book.arch.network/docs/program/utxo.md) - How UTXOs integrate with accounts * [Programs](https://book.arch.network/docs/program/program) - Programs that own and modify accounts * [Instructions](https://book.arch.network/docs/program/instructions-and-messages) - How to interact with accounts [External Resources\ \ External tools, explorers, and resources for Arch Network development](https://book.arch.network/docs/help-resources/resources) [Cross-Program Invocation (CPI)\ \ Next Page](https://book.arch.network/docs/program/cpi) ### On this page [Core Concepts](https://book.arch.network/docs/program/accounts#core-concepts) [Account Fundamentals](https://book.arch.network/docs/program/accounts#account-fundamentals) [Component Details:](https://book.arch.network/docs/program/accounts#component-details) [Account Types & Use Cases](https://book.arch.network/docs/program/accounts#account-types--use-cases) [1\. Program Accounts](https://book.arch.network/docs/program/accounts#1-program-accounts) [2\. Data Accounts](https://book.arch.network/docs/program/accounts#2-data-accounts) [3\. UTXO Accounts](https://book.arch.network/docs/program/accounts#3-utxo-accounts) [Account Interactions](https://book.arch.network/docs/program/accounts#account-interactions) [1\. Creation Patterns](https://book.arch.network/docs/program/accounts#1-creation-patterns) [2\. State Management](https://book.arch.network/docs/program/accounts#2-state-management) [3\. Cross-Program Invocation (CPI)](https://book.arch.network/docs/program/accounts#3-cross-program-invocation-cpi) [Security Considerations](https://book.arch.network/docs/program/accounts#security-considerations) [1\. Access Control](https://book.arch.network/docs/program/accounts#1-access-control) [2\. Data Validation](https://book.arch.network/docs/program/accounts#2-data-validation) [Best Practices](https://book.arch.network/docs/program/accounts#best-practices) [1\. Account Management](https://book.arch.network/docs/program/accounts#1-account-management) [2\. Data Safety](https://book.arch.network/docs/program/accounts#2-data-safety) [3\. Performance](https://book.arch.network/docs/program/accounts#3-performance) [4\. Upgrades](https://book.arch.network/docs/program/accounts#4-upgrades) [Common Patterns](https://book.arch.network/docs/program/accounts#common-patterns) [1\. Account Initialization](https://book.arch.network/docs/program/accounts#1-account-initialization) [2\. Account Updates](https://book.arch.network/docs/program/accounts#2-account-updates) [3\. Account Closure](https://book.arch.network/docs/program/accounts#3-account-closure) [Related Topics](https://book.arch.network/docs/program/accounts#related-topics) --- # Program Program Program ======= A program is a special kind of [account](https://book.arch.network/docs/program/accounts) that contains executable [eBPF](https://ebpf.io/) bytecode, denoted by the `Account.is_executable: true` field. This allows an account to receive arbitrary [instruction](https://book.arch.network/docs/program/instructions-and-messages#instructions) data via a [transaction](https://book.arch.network/docs/sdk/runtime-transaction.md) to be processed by the runtime. Every program is stateless, meaning that it can only read/write data to other accounts and that it cannot write to its own account; this, in-part, is how parallelized execution is made possible (see [State](https://book.arch.network/docs/program/program#4-state) for more info). > Additionally, programs can send instructions to other programs which, in turn, receive instructions and thus extend program composability further. This is known as cross-program invocation (CPI) and will be detailed in future sections. ### [Components:](https://book.arch.network/docs/program/program#components) #### [1\.](https://book.arch.network/docs/program/program#1-entrypoint) [Entrypoint](https://book.arch.network/docs/program/entrypoint) Every Arch program includes a single entrypoint used to invoke the program. A [handler function](https://book.arch.network/docs/program/entrypoint#handler-function) , often named `process_instruction`, is then used to handle the data passed into the entrypoint. These parameters are required for every [instruction](https://book.arch.network/docs/program/instructions-and-messages#instructions) to be processed. use arch_program::entrypoint; entrypoint!(process_instruction); pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { // Program logic here } #### [2\.](https://book.arch.network/docs/program/program#2-instruction) [Instruction](https://book.arch.network/docs/program/instructions-and-messages#instructions) The `instruction_data` is deserialized after being passed into the entrypoint. From there, if there are multiple instructions, a `match` statement can be utilized to point the logic flow to the appropriate handler function previously defined within the program which can continue processing the instruction. #### [3\. Process Instruction](https://book.arch.network/docs/program/program#3-process-instruction) If a program has multiple instructions, a corresponding [handler function](https://book.arch.network/docs/program/entrypoint#handler-function) should be defined to include the specific logic unique to the instruction. #### [4\. State](https://book.arch.network/docs/program/program#4-state) Since programs are stateless, a "data" [account](https://book.arch.network/docs/program/accounts) is needed to hold state for a user. This is a non-executable account that holds program data. If a program receives instruction that results in a user's state being altered, the program would manage this user's state via a mapping within the program's logic. This mapping would link the user's [pubkey](https://book.arch.network/docs/sdk/pubkey.md) with a data [account](https://book.arch.network/docs/program/accounts) where the state would live for that specific program. The program will likely include a struct to define the structure of its state and make it easier to work with. The deserialization of account data occurs during program invocation. After an update is made, state data gets re-serialized into a byte array and stored within the `data` field of the [account](https://book.arch.network/docs/program/accounts) . [Instructions and Messages\ \ Previous Page](https://book.arch.network/docs/program/instructions-and-messages) [Syscalls\ \ Next Page](https://book.arch.network/docs/program/syscall) ### On this page [Components:](https://book.arch.network/docs/program/program#components) [1\.](https://book.arch.network/docs/program/program#1-entrypoint) [Entrypoint](https://book.arch.network/docs/program/entrypoint.md) [2\.](https://book.arch.network/docs/program/program#2-instruction) [Instruction](https://book.arch.network/docs/program/instructions-and-messages.md#instructions) [3\. Process Instruction](https://book.arch.network/docs/program/program#3-process-instruction) [4\. State](https://book.arch.network/docs/program/program#4-state) --- # Building Your First Bitcoin Runes Swap Application DeFi Applications Building Your First Bitcoin Runes Swap Application ================================================== Complete guide to building a decentralized Runes token swap application on Arch Network Welcome to this hands-on tutorial! Today, we're going to build a decentralized application that enables users to swap Bitcoin Runes tokens on the Arch Network. By the end of this lesson, you'll understand how to create a secure, trustless swap mechanism for Runes tokens. [Class Prerequisites](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#class-prerequisites) -------------------------------------------------------------------------------------------------------------------- Before we dive in, please ensure you have: * Completed the [environment setup](https://book.arch.network/docs/quick-start/requirements) * A basic understanding of [Bitcoin Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Familiarity with Rust programming language * Your development environment ready with the Arch Network CLI installed [Lesson 1: Understanding the Basics](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-1-understanding-the-basics) ------------------------------------------------------------------------------------------------------------------------------------------------- ### [What are Runes?](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#what-are-runes) Before we write any code, let's understand what we're working with. Runes is a Bitcoin protocol for fungible tokens, similar to how BRC-20 works. Each Rune token has a unique identifier and can be transferred between Bitcoin addresses. ### [What are we building?](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#what-are-we-building) We're creating a swap program that will: 1. **Allow users to create swap offers** ("I want to trade X amount of Rune A for Y amount of Rune B") 2. **Enable other users to accept these offers** 3. **Let users cancel their offers** if they change their mind 4. **Ensure all swaps are atomic** (they either complete fully or not at all) [Lesson 2: Setting Up Our Project](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-2-setting-up-our-project) --------------------------------------------------------------------------------------------------------------------------------------------- Let's start by creating our project structure. Open your terminal and run: # Create a new directory for your project mkdir runes-swap cd runes-swap # Initialize a new Rust project cargo init --lib # Your project structure should look like this: # runes-swap/ # β”œβ”€β”€ Cargo.toml # β”œβ”€β”€ src/ # β”‚ └── lib.rs [Lesson 3: Defining Our Data Structures](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-3-defining-our-data-structures) --------------------------------------------------------------------------------------------------------------------------------------------------------- Now, let's define the building blocks of our swap program. In programming, it's crucial to plan our data structures before implementing functionality. use arch_program::{ account::AccountInfo, entrypoint, msg, program_error::ProgramError, pubkey::Pubkey, utxo::UtxoMeta, borsh::{BorshDeserialize, BorshSerialize}, }; /// This structure represents a single swap offer in our system #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct SwapOffer { // Unique identifier for the offer pub offer_id: u64, // The public key of the person creating the offer pub maker: Pubkey, // The Rune ID they want to give pub rune_id_give: String, // Amount of Runes they want to give pub amount_give: u64, // The Rune ID they want to receive pub rune_id_want: String, // Amount of Runes they want to receive pub amount_want: u64, // When this offer expires (in block height) pub expiry: u64, // Current status of the offer pub status: OfferStatus, } #[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq)] pub enum OfferStatus { Active, Filled, Cancelled, Expired, } Let's break down why we chose each field: * **`offer_id`**: Every offer needs a unique identifier so we can reference it later * **`maker`**: We store who created the offer to ensure only they can cancel it * **`rune_id_give/want`**: These identify which Runes are being swapped * **`amount_give/want`**: The quantities of each Rune in the swap * **`expiry`**: Offers shouldn't live forever, so we add an expiration * **`status`**: Track whether the offer is still active or has been completed [Lesson 4: Implementing the Swap Logic](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-4-implementing-the-swap-logic) ------------------------------------------------------------------------------------------------------------------------------------------------------- Now that we understand our data structures, let's implement the core swap functionality. We'll start with creating an offer: fn process_create_offer( accounts: &[AccountInfo], instruction: SwapInstruction, ) -> Result<(), ProgramError> { // Step 1: Get all the accounts we need let account_iter = &mut accounts.iter(); let maker = next_account_info(account_iter)?; let offer_account = next_account_info(account_iter)?; let system_program = next_account_info(account_iter)?; // Step 2: Verify the maker is signing this transaction if !maker.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Step 3: Create the swap offer let offer = SwapOffer { offer_id: instruction.offer_id, maker: *maker.key, rune_id_give: instruction.rune_id_give, amount_give: instruction.amount_give, rune_id_want: instruction.rune_id_want, amount_want: instruction.amount_want, expiry: instruction.expiry, status: OfferStatus::Active, }; // Step 4: Store the offer in the account let mut offer_data = offer_account.data.try_borrow_mut().unwrap(); let serialized_offer = offer.try_to_vec() .map_err(|_| ProgramError::InvalidInstructionData)?; offer_data[..serialized_offer.len()].copy_from_slice(&serialized_offer); msg!("Swap offer created with ID: {}", offer.offer_id); Ok(()) } [Lesson 5: Accepting Offers](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-5-accepting-offers) --------------------------------------------------------------------------------------------------------------------------------- Now let's implement the logic for accepting an offer: fn process_accept_offer( accounts: &[AccountInfo], instruction: SwapInstruction, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let taker = next_account_info(account_iter)?; let offer_account = next_account_info(account_iter)?; let maker_account = next_account_info(account_iter)?; // Verify the taker is signing if !taker.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load the existing offer let offer_data = offer_account.data.try_borrow().unwrap(); let mut offer: SwapOffer = SwapOffer::try_from_slice(&offer_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Check if the offer is still active if offer.status != OfferStatus::Active { return Err(ProgramError::InvalidAccountData); } // Check if the offer has expired let current_block_height = arch_program::clock::Clock::get()?.slot; if current_block_height > offer.expiry { offer.status = OfferStatus::Expired; return Err(ProgramError::InvalidAccountData); } // Verify the taker has the required Runes // This would involve checking UTXO balances in a real implementation // Mark the offer as filled offer.status = OfferStatus::Filled; // Update the offer account let mut offer_data_mut = offer_account.data.try_borrow_mut().unwrap(); let serialized_offer = offer.try_to_vec() .map_err(|_| ProgramError::InvalidInstructionData)?; offer_data_mut[..serialized_offer.len()].copy_from_slice(&serialized_offer); msg!("Offer {} accepted by {}", offer.offer_id, taker.key); Ok(()) } [Lesson 6: Cancelling Offers](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-6-cancelling-offers) ----------------------------------------------------------------------------------------------------------------------------------- Let's add the ability for makers to cancel their offers: fn process_cancel_offer( accounts: &[AccountInfo], instruction: SwapInstruction, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let maker = next_account_info(account_iter)?; let offer_account = next_account_info(account_iter)?; // Verify the maker is signing if !maker.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load the existing offer let offer_data = offer_account.data.try_borrow().unwrap(); let mut offer: SwapOffer = SwapOffer::try_from_slice(&offer_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Verify the maker owns this offer if offer.maker != *maker.key { return Err(ProgramError::InvalidAccountData); } // Check if the offer is still active if offer.status != OfferStatus::Active { return Err(ProgramError::InvalidAccountData); } // Mark the offer as cancelled offer.status = OfferStatus::Cancelled; // Update the offer account let mut offer_data_mut = offer_account.data.try_borrow_mut().unwrap(); let serialized_offer = offer.try_to_vec() .map_err(|_| ProgramError::InvalidInstructionData)?; offer_data_mut[..serialized_offer.len()].copy_from_slice(&serialized_offer); msg!("Offer {} cancelled by maker", offer.offer_id); Ok(()) } [Lesson 7: Complete Program Implementation](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-7-complete-program-implementation) --------------------------------------------------------------------------------------------------------------------------------------------------------------- Now let's put it all together in a complete program: use arch_program::{ account::{next_account_info, AccountInfo}, entrypoint, msg, program_error::ProgramError, pubkey::Pubkey, borsh::{BorshDeserialize, BorshSerialize}, }; // Program entry point entrypoint!(process_instruction); pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8], ) -> Result<(), ProgramError> { let instruction = SwapInstruction::try_from_slice(instruction_data) .map_err(|_| ProgramError::InvalidInstructionData)?; match instruction { SwapInstruction::CreateOffer { offer_id, rune_id_give, amount_give, rune_id_want, amount_want, expiry, } => process_create_offer(accounts, SwapInstruction::CreateOffer { offer_id, rune_id_give, amount_give, rune_id_want, amount_want, expiry, }), SwapInstruction::AcceptOffer { offer_id } => { process_accept_offer(accounts, SwapInstruction::AcceptOffer { offer_id }) } SwapInstruction::CancelOffer { offer_id } => { process_cancel_offer(accounts, SwapInstruction::CancelOffer { offer_id }) } } } #[derive(BorshSerialize, BorshDeserialize)] pub enum SwapInstruction { CreateOffer { offer_id: u64, rune_id_give: String, amount_give: u64, rune_id_want: String, amount_want: u64, expiry: u64, }, AcceptOffer { offer_id: u64, }, CancelOffer { offer_id: u64, }, } // ... (include all the functions we defined above) [Lesson 8: Testing Your Swap Program](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-8-testing-your-swap-program) --------------------------------------------------------------------------------------------------------------------------------------------------- ### [Unit Tests](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#unit-tests) #[cfg(test)] mod tests { use super::*; use arch_program::test_utils::*; #[test] fn test_create_offer() { let program_id = Pubkey::new_unique(); let maker = create_test_account(&program_id, 0); let offer_account = create_test_account(&program_id, 1024); let instruction = SwapInstruction::CreateOffer { offer_id: 1, rune_id_give: "DOG".to_string(), amount_give: 1000, rune_id_want: "CAT".to_string(), amount_want: 500, expiry: 1000, }; let result = process_create_offer( &[maker, offer_account], instruction, ); assert!(result.is_ok()); } #[test] fn test_accept_offer() { // Create an active offer first let program_id = Pubkey::new_unique(); let maker = create_test_account(&program_id, 0); let taker = create_test_account(&program_id, 0); let offer_account = create_test_account(&program_id, 1024); // Create the offer let offer = SwapOffer { offer_id: 1, maker: *maker.key, rune_id_give: "DOG".to_string(), amount_give: 1000, rune_id_want: "CAT".to_string(), amount_want: 500, expiry: 1000, status: OfferStatus::Active, }; // Store the offer let mut offer_data = offer_account.data.try_borrow_mut().unwrap(); let serialized_offer = offer.try_to_vec().unwrap(); offer_data[..serialized_offer.len()].copy_from_slice(&serialized_offer); // Accept the offer let instruction = SwapInstruction::AcceptOffer { offer_id: 1 }; let result = process_accept_offer( &[taker, offer_account, maker], instruction, ); assert!(result.is_ok()); } } ### [Integration Tests](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#integration-tests) # Deploy your program cargo build-sbf arch-cli program deploy target/deploy/runes_swap.so # Create a swap offer arch-cli program call \ --accounts ~/offer_account.key \ --instruction-data $(echo '{"CreateOffer":{"offer_id":1,"rune_id_give":"DOG","amount_give":1000,"rune_id_want":"CAT","amount_want":500,"expiry":1000}}' | base64) \ --keypair-path ~/maker.key # Accept the offer arch-cli program call \ --accounts ~/offer_account.key,~/maker_account.key \ --instruction-data $(echo '{"AcceptOffer":{"offer_id":1}}' | base64) \ --keypair-path ~/taker.key [Lesson 9: Advanced Features](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-9-advanced-features) ----------------------------------------------------------------------------------------------------------------------------------- ### [Price Discovery](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#price-discovery) #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct PriceOracle { pub rune_id: String, pub price_in_sats: u64, pub last_updated: u64, } pub fn calculate_swap_price( offer: &SwapOffer, oracle: &PriceOracle, ) -> Result { // Calculate fair price based on oracle data let give_price = oracle.price_in_sats; let want_price = 1000; // This would come from another oracle let fair_amount_want = (offer.amount_give * give_price) / want_price; // Check if the offer is within 5% of fair price let price_tolerance = fair_amount_want / 20; // 5% if offer.amount_want > fair_amount_want + price_tolerance || offer.amount_want < fair_amount_want - price_tolerance { return Err(ProgramError::InvalidInstructionData); } Ok(fair_amount_want) } ### [Liquidity Pools](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#liquidity-pools) #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct LiquidityPool { pub rune_id_a: String, pub rune_id_b: String, pub amount_a: u64, pub amount_b: u64, pub total_liquidity: u64, } pub fn add_liquidity( pool: &mut LiquidityPool, amount_a: u64, amount_b: u64, ) -> Result { if pool.amount_a == 0 && pool.amount_b == 0 { // First liquidity addition pool.amount_a = amount_a; pool.amount_b = amount_b; pool.total_liquidity = amount_a + amount_b; return Ok(pool.total_liquidity); } // Calculate proportional liquidity let liquidity_a = (amount_a * pool.total_liquidity) / pool.amount_a; let liquidity_b = (amount_b * pool.total_liquidity) / pool.amount_b; let liquidity_to_add = liquidity_a.min(liquidity_b); pool.amount_a += amount_a; pool.amount_b += amount_b; pool.total_liquidity += liquidity_to_add; Ok(liquidity_to_add) } [Lesson 10: Security Considerations](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-10-security-considerations) ------------------------------------------------------------------------------------------------------------------------------------------------- ### [Input Validation](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#input-validation) pub fn validate_offer(offer: &SwapOffer) -> Result<(), ProgramError> { // Check for reasonable amounts if offer.amount_give == 0 || offer.amount_want == 0 { return Err(ProgramError::InvalidInstructionData); } // Check for reasonable expiry (not too far in the future) let current_slot = arch_program::clock::Clock::get()?.slot; if offer.expiry > current_slot + 10000 { // Max 10k slots ahead return Err(ProgramError::InvalidInstructionData); } // Validate Rune IDs if offer.rune_id_give.is_empty() || offer.rune_id_want.is_empty() { return Err(ProgramError::InvalidInstructionData); } // Prevent self-swaps if offer.rune_id_give == offer.rune_id_want { return Err(ProgramError::InvalidInstructionData); } Ok(()) } ### [Access Control](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#access-control) pub fn verify_offer_ownership( offer: &SwapOffer, signer: &Pubkey, ) -> Result<(), ProgramError> { if offer.maker != *signer { return Err(ProgramError::InvalidAccountData); } Ok(()) } [Lesson 11: Deployment and Testing](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-11-deployment-and-testing) ----------------------------------------------------------------------------------------------------------------------------------------------- ### [Build and Deploy](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#build-and-deploy) # Build the program cargo build-sbf # Deploy to local network arch-cli program deploy target/deploy/runes_swap.so # Deploy to testnet arch-cli program deploy target/deploy/runes_swap.so --url testnet ### [Create Test Accounts](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#create-test-accounts) # Create test keypairs openssl rand -out ~/maker.key 32 openssl rand -out ~/taker.key 32 openssl rand -out ~/offer_account.key 32 # Fund accounts arch-cli account airdrop --keypair-path ~/maker.key arch-cli account airdrop --keypair-path ~/taker.key ### [Test the Complete Flow](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#test-the-complete-flow) # 1. Create an offer arch-cli program call \ --accounts ~/offer_account.key \ --instruction-data $(echo '{"CreateOffer":{"offer_id":1,"rune_id_give":"DOG","amount_give":1000,"rune_id_want":"CAT","amount_want":500,"expiry":1000}}' | base64) \ --keypair-path ~/maker.key # 2. Check the offer status arch-cli account show ~/offer_account.key # 3. Accept the offer arch-cli program call \ --accounts ~/offer_account.key,~/maker_account.key \ --instruction-data $(echo '{"AcceptOffer":{"offer_id":1}}' | base64) \ --keypair-path ~/taker.key # 4. Verify the offer is filled arch-cli account show ~/offer_account.key [Best Practices](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#best-practices) ---------------------------------------------------------------------------------------------------------- ### [1\. Error Handling](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#1-error-handling) * Always validate inputs thoroughly * Provide meaningful error messages * Handle edge cases gracefully ### [2\. Security](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#2-security) * Verify all signatures and ownership * Implement proper access controls * Use secure random number generation for IDs ### [3\. Performance](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#3-performance) * Optimize data structures for minimal storage * Use efficient serialization/deserialization * Consider gas costs in your design ### [4\. User Experience](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#4-user-experience) * Provide clear error messages * Implement proper status tracking * Add helpful logging for debugging [Next Steps](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#next-steps) -------------------------------------------------------------------------------------------------- [### Lending Protocol Guide\ \ Build a lending protocol using your swap knowledge](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol) [### Oracle Integration\ \ Add price oracles to your swap](https://book.arch.network/docs/development/how-to-write-oracle-program) [### APL Token Program\ \ Learn about the built-in token program](https://book.arch.network/docs/APL/token-program) [### Arch Examples\ \ Explore more example programs](https://github.com/Arch-Network/arch-examples) [Resources](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#resources) ------------------------------------------------------------------------------------------------ [### Arch Examples Repository\ \ Complete swap implementation examples](https://github.com/Arch-Network/arch-examples) [### Bitcoin Integration\ \ Understand Bitcoin integration in Arch](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Program Development\ \ Master Arch program development](https://book.arch.network/docs/development/writing-your-first-program) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [How to Build a Bitcoin Lending Protocol\ \ Complete guide to building a decentralized lending protocol for Bitcoin-based assets on Arch Network](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol) [Creating APL Tokens on Arch Network\ \ Complete guide to creating and managing fungible tokens using the APL Token Program](https://book.arch.network/docs/development/how-to-create-a-fungible-token) ### On this page [Class Prerequisites](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#class-prerequisites) [Lesson 1: Understanding the Basics](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-1-understanding-the-basics) [What are Runes?](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#what-are-runes) [What are we building?](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#what-are-we-building) [Lesson 2: Setting Up Our Project](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-2-setting-up-our-project) [Lesson 3: Defining Our Data Structures](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-3-defining-our-data-structures) [Lesson 4: Implementing the Swap Logic](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-4-implementing-the-swap-logic) [Lesson 5: Accepting Offers](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-5-accepting-offers) [Lesson 6: Cancelling Offers](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-6-cancelling-offers) [Lesson 7: Complete Program Implementation](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-7-complete-program-implementation) [Lesson 8: Testing Your Swap Program](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-8-testing-your-swap-program) [Unit Tests](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#unit-tests) [Integration Tests](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#integration-tests) [Lesson 9: Advanced Features](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-9-advanced-features) [Price Discovery](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#price-discovery) [Liquidity Pools](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#liquidity-pools) [Lesson 10: Security Considerations](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-10-security-considerations) [Input Validation](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#input-validation) [Access Control](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#access-control) [Lesson 11: Deployment and Testing](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#lesson-11-deployment-and-testing) [Build and Deploy](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#build-and-deploy) [Create Test Accounts](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#create-test-accounts) [Test the Complete Flow](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#test-the-complete-flow) [Best Practices](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#best-practices) [1\. Error Handling](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#1-error-handling) [2\. Security](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#2-security) [3\. Performance](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#3-performance) [4\. User Experience](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#4-user-experience) [Next Steps](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#next-steps) [Resources](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap#resources) --- # How to Build a Bitcoin Lending Protocol DeFi Applications How to Build a Bitcoin Lending Protocol ======================================= Complete guide to building a decentralized lending protocol for Bitcoin-based assets on Arch Network This guide walks through building a lending protocol for Bitcoin-based assets (BTC, Runes, Ordinals) on Arch Network. We'll create a decentralized lending platform similar to Aave, but specifically designed for Bitcoin-based assets. [Prerequisites](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#prerequisites) -------------------------------------------------------------------------------------------------------------- Before starting, ensure you have: * Completed the [environment setup](https://book.arch.network/docs/quick-start/requirements) * A basic understanding of [Bitcoin Integration](https://book.arch.network/docs/core-concepts/bitcoin-integration) * Familiarity with Rust programming language * Your development environment ready with the Arch CLI installed [System Overview](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#system-overview) ------------------------------------------------------------------------------------------------------------------ ### [Basic User Flow](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#basic-user-flow) ### [Safety System](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#safety-system) ### [Simple Example](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#simple-example) Let's say Alice wants to borrow BTC and Bob wants to earn interest: 1. **Bob (Lender)** * Deposits 1 BTC into pool * Earns 3% APY interest 2. **Alice (Borrower)** * Provides 1.5 BTC as collateral * Borrows 1 BTC * Pays 5% APY interest 3. **Safety System** * Monitors BTC price * Checks if Alice's collateral stays valuable enough * If BTC price drops too much, liquidates some collateral to protect Bob's deposit [Architecture Overview](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#architecture-overview) ------------------------------------------------------------------------------------------------------------------------------ Our lending protocol consists of several key components: ### [1\. Pool Accounts](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-pool-accounts) Pool accounts are the core of our lending protocol. They serve as liquidity pools where users can: * **Deposit Bitcoin-based assets** (BTC, Runes, Ordinals) * **Earn interest on deposits** * **Borrow against their collateral** * **Manage protocol parameters** Each pool account maintains: * Total deposits and borrows * Interest rates and utilization metrics * Collateral factors and liquidation thresholds * Asset-specific parameters The pool account manages both state and UTXOs: * **State Management**: Tracks deposits, withdrawals, and user positions * **UTXO Management**: * Maintains a collection of UTXOs for the pool's Bitcoin holdings * Manages UTXO creation for withdrawals * Handles UTXO consolidation for efficient liquidity management ### [2\. Price Oracle](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-price-oracle) Track asset prices for liquidation calculations ### [3\. User Positions](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-user-positions) User positions track all user interactions with the lending pools: * Active deposits and their earned interest * Active borrows and their accrued interest * Collateral values and health factors * Liquidation history and penalties [Data Structures](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#data-structures) ------------------------------------------------------------------------------------------------------------------ ### [Pool Account](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#pool-account) use arch_program::prelude::*; use borsh::{BorshDeserialize, BorshSerialize}; #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct LendingPool { // Pool identification pub pool_id: u64, pub asset_type: AssetType, // Pool state pub total_deposits: u64, pub total_borrows: u64, pub utilization_rate: u64, // Basis points (0-10000) // Interest rates pub deposit_rate: u64, // Basis points pub borrow_rate: u64, // Basis points // Risk parameters pub collateral_factor: u64, // Basis points pub liquidation_threshold: u64, // Basis points pub liquidation_penalty: u64, // Basis points // Oracle integration pub price_oracle: Pubkey, pub last_price_update: i64, // Pool management pub pool_authority: Pubkey, pub is_active: bool, pub created_at: i64, } #[derive(BorshSerialize, BorshDeserialize, Debug, Clone)] pub enum AssetType { Bitcoin, Rune { rune_id: String }, Ordinal { inscription_id: String }, } ### [User Position](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#user-position) #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct UserPosition { // User identification pub user: Pubkey, pub position_id: u64, // Deposits pub deposits: Vec, pub total_deposit_value: u64, // Borrows pub borrows: Vec, pub total_borrow_value: u64, // Health factor pub health_factor: u64, // Basis points pub is_healthy: bool, // Liquidation pub liquidation_count: u32, pub last_liquidation: Option, // Timestamps pub created_at: i64, pub last_updated: i64, } #[derive(BorshSerialize, BorshDeserialize, Debug, Clone)] pub struct Deposit { pub pool_id: u64, pub amount: u64, pub interest_earned: u64, pub deposited_at: i64, pub last_interest_update: i64, } #[derive(BorshSerialize, BorshDeserialize, Debug, Clone)] pub struct Borrow { pub pool_id: u64, pub amount: u64, pub interest_accrued: u64, pub borrowed_at: i64, pub last_interest_update: i64, } [Core Instructions](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#core-instructions) ---------------------------------------------------------------------------------------------------------------------- ### [Initialize Pool](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#initialize-pool) pub fn initialize_pool( program_id: &Pubkey, accounts: &[AccountInfo], pool_id: u64, asset_type: AssetType, collateral_factor: u64, liquidation_threshold: u64, price_oracle: Pubkey, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let pool_account = next_account_info(account_iter)?; let authority = next_account_info(account_iter)?; let system_program = next_account_info(account_iter)?; // Verify authority if !authority.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Initialize pool let pool = LendingPool { pool_id, asset_type, total_deposits: 0, total_borrows: 0, utilization_rate: 0, deposit_rate: 0, borrow_rate: 0, collateral_factor, liquidation_threshold, liquidation_penalty: 500, // 5% default price_oracle, last_price_update: 0, pool_authority: *authority.key, is_active: true, created_at: arch_program::clock::Clock::get()?.unix_timestamp, }; // Store pool data let mut pool_data = pool_account.data.try_borrow_mut().unwrap(); let serialized = pool.try_to_vec().unwrap(); pool_data[..serialized.len()].copy_from_slice(&serialized); Ok(()) } ### [Deposit Assets](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#deposit-assets) pub fn deposit( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let pool_account = next_account_info(account_iter)?; let user_position = next_account_info(account_iter)?; let user = next_account_info(account_iter)?; let utxo_account = next_account_info(account_iter)?; // Verify user is signer if !user.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load pool data let pool_data = pool_account.data.try_borrow().unwrap(); let mut pool: LendingPool = LendingPool::try_from_slice(&pool_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Load user position let position_data = user_position.data.try_borrow().unwrap(); let mut position: UserPosition = UserPosition::try_from_slice(&position_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Update pool state pool.total_deposits += amount; pool.utilization_rate = (pool.total_borrows * 10000) / pool.total_deposits; // Update interest rates based on utilization update_interest_rates(&mut pool); // Add deposit to user position let deposit = Deposit { pool_id: pool.pool_id, amount, interest_earned: 0, deposited_at: arch_program::clock::Clock::get()?.unix_timestamp, last_interest_update: arch_program::clock::Clock::get()?.unix_timestamp, }; position.deposits.push(deposit); position.total_deposit_value += amount; position.last_updated = arch_program::clock::Clock::get()?.unix_timestamp; // Update health factor update_health_factor(&mut position, &pool); // Store updated data let mut pool_data_mut = pool_account.data.try_borrow_mut().unwrap(); let serialized_pool = pool.try_to_vec().unwrap(); pool_data_mut[..serialized_pool.len()].copy_from_slice(&serialized_pool); let mut position_data_mut = user_position.data.try_borrow_mut().unwrap(); let serialized_position = position.try_to_vec().unwrap(); position_data_mut[..serialized_position.len()].copy_from_slice(&serialized_position); Ok(()) } ### [Borrow Assets](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#borrow-assets) pub fn borrow( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let pool_account = next_account_info(account_iter)?; let user_position = next_account_info(account_iter)?; let user = next_account_info(account_iter)?; let destination_utxo = next_account_info(account_iter)?; // Verify user is signer if !user.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load pool data let pool_data = pool_account.data.try_borrow().unwrap(); let mut pool: LendingPool = LendingPool::try_from_slice(&pool_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Load user position let position_data = user_position.data.try_borrow().unwrap(); let mut position: UserPosition = UserPosition::try_from_slice(&position_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Check if pool has sufficient liquidity if pool.total_deposits - pool.total_borrows < amount { return Err(ProgramError::InsufficientFunds); } // Check health factor after borrow let new_borrow_value = position.total_borrow_value + amount; let health_factor = calculate_health_factor( position.total_deposit_value, new_borrow_value, pool.collateral_factor, ); if health_factor < 10000 { // Less than 100% collateralized return Err(ProgramError::InvalidAccountData); } // Update pool state pool.total_borrows += amount; pool.utilization_rate = (pool.total_borrows * 10000) / pool.total_deposits; update_interest_rates(&mut pool); // Add borrow to user position let borrow = Borrow { pool_id: pool.pool_id, amount, interest_accrued: 0, borrowed_at: arch_program::clock::Clock::get()?.unix_timestamp, last_interest_update: arch_program::clock::Clock::get()?.unix_timestamp, }; position.borrows.push(borrow); position.total_borrow_value += amount; position.last_updated = arch_program::clock::Clock::get()?.unix_timestamp; // Update health factor update_health_factor(&mut position, &pool); // Store updated data let mut pool_data_mut = pool_account.data.try_borrow_mut().unwrap(); let serialized_pool = pool.try_to_vec().unwrap(); pool_data_mut[..serialized_pool.len()].copy_from_slice(&serialized_pool); let mut position_data_mut = user_position.data.try_borrow_mut().unwrap(); let serialized_position = position.try_to_vec().unwrap(); position_data_mut[..serialized_position.len()].copy_from_slice(&serialized_position); Ok(()) } [Interest Rate Calculation](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#interest-rate-calculation) -------------------------------------------------------------------------------------------------------------------------------------- fn update_interest_rates(pool: &mut LendingPool) { let utilization = pool.utilization_rate; // Linear interest rate model // Base rate + (utilization * slope) let base_rate = 200; // 2% base rate let slope = 300; // 3% slope pool.borrow_rate = base_rate + (utilization * slope / 10000); // Deposit rate is borrow rate * utilization * (1 - reserve factor) let reserve_factor = 1000; // 10% reserve factor pool.deposit_rate = (pool.borrow_rate * utilization * (10000 - reserve_factor)) / (10000 * 10000); } [Health Factor Calculation](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#health-factor-calculation) -------------------------------------------------------------------------------------------------------------------------------------- fn calculate_health_factor( total_deposit_value: u64, total_borrow_value: u64, collateral_factor: u64, ) -> u64 { if total_borrow_value == 0 { return u64::MAX; // No borrows = healthy } let collateral_value = total_deposit_value * collateral_factor / 10000; (collateral_value * 10000) / total_borrow_value } fn update_health_factor(position: &mut UserPosition, pool: &LendingPool) { position.health_factor = calculate_health_factor( position.total_deposit_value, position.total_borrow_value, pool.collateral_factor, ); position.is_healthy = position.health_factor >= 10000; } [Liquidation System](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#liquidation-system) ------------------------------------------------------------------------------------------------------------------------ ### [Liquidate Position](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#liquidate-position) pub fn liquidate( program_id: &Pubkey, accounts: &[AccountInfo], liquidate_amount: u64, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let pool_account = next_account_info(account_iter)?; let user_position = next_account_info(account_iter)?; let liquidator = next_account_info(account_iter)?; let liquidator_position = next_account_info(account_iter)?; // Verify liquidator is signer if !liquidator.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load pool data let pool_data = pool_account.data.try_borrow().unwrap(); let pool: LendingPool = LendingPool::try_from_slice(&pool_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Load user position let position_data = user_position.data.try_borrow().unwrap(); let mut position: UserPosition = UserPosition::try_from_slice(&position_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Check if position is unhealthy if position.is_healthy { return Err(ProgramError::InvalidAccountData); } // Calculate liquidation amount let max_liquidation = position.total_deposit_value * 5000 / 10000; // Max 50% of deposits let actual_liquidation = liquidate_amount.min(max_liquidation); // Apply liquidation penalty let penalty_amount = actual_liquidation * pool.liquidation_penalty / 10000; let liquidator_reward = actual_liquidation + penalty_amount; // Update position position.total_deposit_value -= actual_liquidation; position.liquidation_count += 1; position.last_liquidation = Some(arch_program::clock::Clock::get()?.unix_timestamp); // Update health factor update_health_factor(&mut position, &pool); // Store updated position let mut position_data_mut = user_position.data.try_borrow_mut().unwrap(); let serialized_position = position.try_to_vec().unwrap(); position_data_mut[..serialized_position.len()].copy_from_slice(&serialized_position); Ok(()) } [Oracle Integration](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#oracle-integration) ------------------------------------------------------------------------------------------------------------------------ ### [Price Update](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#price-update) pub fn update_price( program_id: &Pubkey, accounts: &[AccountInfo], new_price: u64, ) -> Result<(), ProgramError> { let account_iter = &mut accounts.iter(); let pool_account = next_account_info(account_iter)?; let oracle = next_account_info(account_iter)?; // Verify oracle authority if !oracle.is_signer { return Err(ProgramError::MissingRequiredSignature); } // Load pool data let pool_data = pool_account.data.try_borrow().unwrap(); let mut pool: LendingPool = LendingPool::try_from_slice(&pool_data) .map_err(|_| ProgramError::InvalidAccountData)?; // Verify oracle matches if *oracle.key != pool.price_oracle { return Err(ProgramError::InvalidAccountData); } // Update price and timestamp pool.last_price_update = arch_program::clock::Clock::get()?.unix_timestamp; // Store updated pool let mut pool_data_mut = pool_account.data.try_borrow_mut().unwrap(); let serialized_pool = pool.try_to_vec().unwrap(); pool_data_mut[..serialized_pool.len()].copy_from_slice(&serialized_pool); Ok(()) } [Testing](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#testing) -------------------------------------------------------------------------------------------------- ### [Unit Tests](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#unit-tests) #[cfg(test)] mod tests { use super::*; use arch_program::test_utils::*; #[test] fn test_pool_initialization() { let program_id = Pubkey::new_unique(); let pool_account = create_test_account(&program_id, 1024); let authority = create_test_account(&program_id, 0); let asset_type = AssetType::Bitcoin; let result = initialize_pool( &program_id, &[pool_account, authority], 1, asset_type, 8000, // 80% collateral factor 8500, // 85% liquidation threshold Pubkey::new_unique(), ); assert!(result.is_ok()); } #[test] fn test_deposit() { let program_id = Pubkey::new_unique(); let pool_account = create_test_account(&program_id, 1024); let user_position = create_test_account(&program_id, 1024); let user = create_test_account(&program_id, 0); let result = deposit( &program_id, &[pool_account, user_position, user], 1000000, // 1 BTC in satoshis ); assert!(result.is_ok()); } #[test] fn test_health_factor_calculation() { let health_factor = calculate_health_factor( 1000000, // 1 BTC deposits 500000, // 0.5 BTC borrows 8000, // 80% collateral factor ); assert_eq!(health_factor, 16000); // 160% collateralized } } [Deployment](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#deployment) -------------------------------------------------------------------------------------------------------- ### [Build and Deploy](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#build-and-deploy) # Build the program cargo build-sbf # Deploy to local network arch-cli program deploy target/deploy/lending_protocol.so # Deploy to testnet arch-cli program deploy target/deploy/lending_protocol.so --url testnet ### [Initialize Pool](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#initialize-pool-1) # Initialize a Bitcoin lending pool arch-cli program call \ --accounts ~/pool_account.key,~/authority.key \ --instruction-data $(echo '{"InitializePool":{"pool_id":1,"asset_type":"Bitcoin","collateral_factor":8000,"liquidation_threshold":8500,"price_oracle":""}}' | base64) \ --keypair-path ~/authority.key [Security Considerations](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#security-considerations) ---------------------------------------------------------------------------------------------------------------------------------- ### [1\. Oracle Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-oracle-security) * Use multiple price sources * Implement price deviation checks * Add circuit breakers for extreme price movements ### [2\. Liquidation Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-liquidation-security) * Implement proper liquidation incentives * Add liquidation caps to prevent over-liquidation * Monitor liquidation patterns for abuse ### [3\. Interest Rate Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-interest-rate-security) * Implement rate limits for interest rate changes * Add emergency pause functionality * Monitor for interest rate manipulation ### [4\. Access Control](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#4-access-control) * Implement proper authority management * Add multi-signature requirements for critical operations * Regular security audits [Best Practices](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#best-practices) ---------------------------------------------------------------------------------------------------------------- ### [1\. Risk Management](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-risk-management) * Conservative collateral factors * Regular health factor monitoring * Automated liquidation systems ### [2\. User Experience](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-user-experience) * Clear health factor displays * Liquidation warnings * Easy deposit/withdrawal flows ### [3\. Protocol Governance](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-protocol-governance) * Community-driven parameter updates * Transparent decision making * Regular protocol upgrades [Next Steps](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#next-steps) -------------------------------------------------------------------------------------------------------- [### Oracle Program Guide\ \ Learn to build price oracles for your lending protocol](https://book.arch.network/docs/development/how-to-write-oracle-program) [### Runes Swap Guide\ \ Build a token swap protocol](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap) [### APL Token Program\ \ Use APL tokens in your lending protocol](https://book.arch.network/docs/APL/token-program) [### Arch Examples\ \ Explore more example programs](https://github.com/Arch-Network/arch-examples) [Resources](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#resources) ------------------------------------------------------------------------------------------------------ [### Arch Examples Repository\ \ Complete lending protocol implementation](https://github.com/Arch-Network/arch-examples) [### Bitcoin Integration\ \ Understand Bitcoin integration in Arch](https://book.arch.network/docs/core-concepts/bitcoin-integration) [### Program Development\ \ Master Arch program development](https://book.arch.network/docs/development/writing-your-first-program) [### Community Discord\ \ Get help from the community](https://discord.gg/archnetwork) [ROAST and FROST Consensus\ \ Arch's consensus mechanism combining ROAST and FROST for secure, efficient distributed consensus](https://book.arch.network/docs/core-concepts/consensus) [Building Your First Bitcoin Runes Swap Application\ \ Complete guide to building a decentralized Runes token swap application on Arch Network](https://book.arch.network/docs/defi-applications/how-to-build-runes-swap) ### On this page [Prerequisites](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#prerequisites) [System Overview](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#system-overview) [Basic User Flow](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#basic-user-flow) [Safety System](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#safety-system) [Simple Example](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#simple-example) [Architecture Overview](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#architecture-overview) [1\. Pool Accounts](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-pool-accounts) [2\. Price Oracle](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-price-oracle) [3\. User Positions](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-user-positions) [Data Structures](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#data-structures) [Pool Account](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#pool-account) [User Position](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#user-position) [Core Instructions](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#core-instructions) [Initialize Pool](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#initialize-pool) [Deposit Assets](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#deposit-assets) [Borrow Assets](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#borrow-assets) [Interest Rate Calculation](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#interest-rate-calculation) [Health Factor Calculation](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#health-factor-calculation) [Liquidation System](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#liquidation-system) [Liquidate Position](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#liquidate-position) [Oracle Integration](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#oracle-integration) [Price Update](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#price-update) [Testing](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#testing) [Unit Tests](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#unit-tests) [Deployment](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#deployment) [Build and Deploy](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#build-and-deploy) [Initialize Pool](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#initialize-pool-1) [Security Considerations](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#security-considerations) [1\. Oracle Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-oracle-security) [2\. Liquidation Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-liquidation-security) [3\. Interest Rate Security](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-interest-rate-security) [4\. Access Control](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#4-access-control) [Best Practices](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#best-practices) [1\. Risk Management](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#1-risk-management) [2\. User Experience](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#2-user-experience) [3\. Protocol Governance](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#3-protocol-governance) [Next Steps](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#next-steps) [Resources](https://book.arch.network/docs/defi-applications/how-to-build-lending-protocol#resources) --- # External Resources Help Resources External Resources ================== External tools, explorers, and resources for Arch Network development [Resources](https://book.arch.network/docs/help-resources/resources#resources) =============================================================================== [Bitcoin Mempool and Blockchain Explorer](https://book.arch.network/docs/help-resources/resources#bitcoin-mempool-and-blockchain-explorer) ------------------------------------------------------------------------------------------------------------------------------------------- ### [Arch Regtest Explorer](https://book.arch.network/docs/help-resources/resources#arch-regtest-explorer) * **[mempool.space - Arch Regtest](https://mempool.dev.aws.archnetwork.xyz/) ** - Bitcoin mempool and block explorer. This mempool.space instance monitors the regtest Bitcoin blockchain being used to run and validate all examples in this repository. ### [General Bitcoin Resources](https://book.arch.network/docs/help-resources/resources#general-bitcoin-resources) * **[mempool.space](https://mempool.space/) ** - Main Bitcoin mempool and block explorer * **[Blockstream Explorer](https://blockstream.info/) ** - Bitcoin blockchain explorer * **[Bitcoin Core Documentation](https://bitcoin.org/en/developer-documentation) ** - Official Bitcoin development documentation [Development Tools](https://book.arch.network/docs/help-resources/resources#development-tools) ----------------------------------------------------------------------------------------------- ### [Solana Development](https://book.arch.network/docs/help-resources/resources#solana-development) * **[Solana CLI](https://docs.solanalabs.com/cli/install) ** - Command-line interface for Solana development * **[Solana Local Development Guide](https://solana.com/developers/guides/getstarted/setup-local-development) ** - Official guide for local Solana development * **[Solana Program Library](https://spl.solana.com/) ** - Standard programs for Solana * **[Anchor Framework](https://www.anchor-lang.com/) ** - Framework for Solana program development ### [Rust Development](https://book.arch.network/docs/help-resources/resources#rust-development) * **[Rust Book](https://doc.rust-lang.org/book/) ** - Official Rust programming language book * **[Rust by Example](https://doc.rust-lang.org/rust-by-example/) ** - Learn Rust through examples * **[Cargo Book](https://doc.rust-lang.org/cargo/) ** - Rust's package manager and build system * **[Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) ** - Guidelines for Rust API design [Arch Network Resources](https://book.arch.network/docs/help-resources/resources#arch-network-resources) --------------------------------------------------------------------------------------------------------- ### [Official Repositories](https://book.arch.network/docs/help-resources/resources#official-repositories) * **[Arch Network Main Repository](https://github.com/Arch-Network/arch-network) ** - Core Arch Network implementation * **[Arch Examples](https://github.com/Arch-Network/arch-examples) ** - Example programs and tutorials * **[Arch CLI](https://github.com/Arch-Network/arch-node) ** - Command-line interface and tools ### [Community Resources](https://book.arch.network/docs/help-resources/resources#community-resources) * **[Discord Community](https://discord.gg/archnetwork) ** - Join our developer community * **[GitHub Discussions](https://github.com/Arch-Network/arch-network/discussions) ** - Community discussions and Q&A * **[Arch Network Website](https://arch.network/) ** - Official website and announcements [Bitcoin Development Resources](https://book.arch.network/docs/help-resources/resources#bitcoin-development-resources) ----------------------------------------------------------------------------------------------------------------------- ### [Bitcoin Core](https://book.arch.network/docs/help-resources/resources#bitcoin-core) * **[Bitcoin Core](https://bitcoincore.org/) ** - Official Bitcoin implementation * **[Bitcoin Developer Guide](https://bitcoin.org/en/developer-guide) ** - Comprehensive development guide * **[Bitcoin Improvement Proposals (BIPs)](https://github.com/bitcoin/bips) ** - Bitcoin protocol improvements * **[Bitcoin Script](https://en.bitcoin.it/wiki/Script) ** - Bitcoin's scripting language ### [Bitcoin Libraries](https://book.arch.network/docs/help-resources/resources#bitcoin-libraries) * **[Bitcoin Core RPC](https://developer.bitcoin.org/reference/rpc/) ** - Bitcoin Core RPC API reference * **[bitcoindevkit](https://github.com/bitcoindevkit) ** - Rust library for Bitcoin development * **[bitcoinjs-lib](https://github.com/bitcoinjs/bitcoinjs-lib) ** - JavaScript Bitcoin library * **[python-bitcoinlib](https://github.com/petertodd/python-bitcoinlib) ** - Python Bitcoin library [Cryptographic Resources](https://book.arch.network/docs/help-resources/resources#cryptographic-resources) ----------------------------------------------------------------------------------------------------------- ### [Threshold Signatures](https://book.arch.network/docs/help-resources/resources#threshold-signatures) * **[FROST Paper](https://eprint.iacr.org/2020/852.pdf) ** - Flexible Round-Optimized Schnorr Threshold Signatures * **[ROAST Paper](https://eprint.iacr.org/2022/550.pdf) ** - Robust Asynchronous Schnorr Threshold Signatures * **[FROST Implementation](https://github.com/ZcashFoundation/frost) ** - Reference implementation by Zcash Foundation ### [Schnorr Signatures](https://book.arch.network/docs/help-resources/resources#schnorr-signatures) * **[BIP 340](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki) ** - Schnorr Signatures for secp256k1 * **[BIP 341](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki) ** - Taproot: SegWit version 1 spending rules * **[BIP 342](https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki) ** - Validation of Taproot Scripts [Development Environment](https://book.arch.network/docs/help-resources/resources#development-environment) ----------------------------------------------------------------------------------------------------------- ### [Docker Resources](https://book.arch.network/docs/help-resources/resources#docker-resources) * **[Docker Documentation](https://docs.docker.com/) ** - Official Docker documentation * **[Docker Compose](https://docs.docker.com/compose/) ** - Multi-container Docker applications * **[OrbStack](https://orbstack.dev/) ** - Lightweight Docker alternative for macOS ### [IDE and Editor Extensions](https://book.arch.network/docs/help-resources/resources#ide-and-editor-extensions) #### [VS Code Extensions](https://book.arch.network/docs/help-resources/resources#vs-code-extensions) * **Rust Analyzer** - Rust language support * **Solana** - Solana program development * **GitLens** - Enhanced Git capabilities * **Thunder Client** - API testing * **Markdown All in One** - Markdown support #### [Other Editors](https://book.arch.network/docs/help-resources/resources#other-editors) * **IntelliJ Rust** - Rust plugin for IntelliJ IDEA * **Vim/Neovim** - Rust support with rust.vim * **Emacs** - Rust support with rust-mode [Testing and Debugging](https://book.arch.network/docs/help-resources/resources#testing-and-debugging) ------------------------------------------------------------------------------------------------------- ### [Testing Frameworks](https://book.arch.network/docs/help-resources/resources#testing-frameworks) * **[Rust Testing](https://doc.rust-lang.org/book/ch11-00-testing.html) ** - Built-in Rust testing framework * **[Criterion](https://github.com/bheisler/criterion.rs) ** - Statistics-driven benchmarking * **[Mockall](https://github.com/asomers/mockall) ** - Mocking framework for Rust ### [Debugging Tools](https://book.arch.network/docs/help-resources/resources#debugging-tools) * **[GDB](https://www.gnu.org/software/gdb/) ** - GNU Debugger * **[LLDB](https://lldb.llvm.org/) ** - LLVM Debugger * **[Valgrind](https://valgrind.org/) ** - Memory debugging and profiling [Security Resources](https://book.arch.network/docs/help-resources/resources#security-resources) ------------------------------------------------------------------------------------------------- ### [Security Best Practices](https://book.arch.network/docs/help-resources/resources#security-best-practices) * **[Rust Security Guidelines](https://github.com/rust-lang/rust-security-policy) ** - Rust security policies * **[OWASP Top 10](https://owasp.org/www-project-top-ten/) ** - Common web application security risks * **[Bitcoin Security Best Practices](https://bitcoin.org/en/secure-your-wallet) ** - Bitcoin security guidelines ### [Auditing Tools](https://book.arch.network/docs/help-resources/resources#auditing-tools) * **[Cargo Audit](https://github.com/RustSec/cargo-audit) ** - Audit Cargo dependencies for security vulnerabilities * **[Clippy](https://github.com/rust-lang/rust-clippy) ** - Rust linter for catching common mistakes * **[Rustfmt](https://github.com/rust-lang/rustfmt) ** - Rust code formatter [Learning Resources](https://book.arch.network/docs/help-resources/resources#learning-resources) ------------------------------------------------------------------------------------------------- ### [Online Courses](https://book.arch.network/docs/help-resources/resources#online-courses) * **[Rustlings](https://github.com/rust-lang/rustlings) ** - Interactive Rust exercises * **[Rust by Practice](https://practice.rs/) ** - Learn Rust through practice * **[Bitcoin Development Course](https://bitcoinbook.info/) ** - Programming Bitcoin book and course ### [Books](https://book.arch.network/docs/help-resources/resources#books) * **[Programming Bitcoin](https://github.com/jimmysong/programmingbitcoin) ** - Learn Bitcoin programming * **[Mastering Bitcoin](https://github.com/bitcoinbook/bitcoinbook) ** - Technical guide to Bitcoin * **[The Rust Programming Language](https://doc.rust-lang.org/book/) ** - Official Rust book [Community and Support](https://book.arch.network/docs/help-resources/resources#community-and-support) ------------------------------------------------------------------------------------------------------- ### [Forums and Communities](https://book.arch.network/docs/help-resources/resources#forums-and-communities) * **[Bitcoin Stack Exchange](https://bitcoin.stackexchange.com/) ** - Q&A for Bitcoin developers * **[Rust Users Forum](https://users.rust-lang.org/) ** - Community forum for Rust users * **[Solana Discord](https://discord.gg/solana) ** - Solana developer community ### [News and Updates](https://book.arch.network/docs/help-resources/resources#news-and-updates) * **[Bitcoin Magazine](https://bitcoinmagazine.com/) ** - Bitcoin news and analysis * **[The Rust Blog](https://blog.rust-lang.org/) ** - Official Rust blog * **[Solana Blog](https://solana.com/news) ** - Solana news and updates [Need More Help?](https://book.arch.network/docs/help-resources/resources#need-more-help) ------------------------------------------------------------------------------------------ [### Join Discord\ \ Get help from the community](https://discord.gg/archnetwork) [### GitHub Issues\ \ Report bugs and request features](https://github.com/Arch-Network/arch-network/issues) [### Documentation\ \ Browse our comprehensive guides](https://book.arch.network/docs) [### Examples\ \ Study example programs](https://github.com/Arch-Network/arch-examples) [FAQ\ \ Frequently asked questions about Arch Network development](https://book.arch.network/docs/help-resources/faq) [Account Guide\ \ Next Page](https://book.arch.network/docs/program/accounts) ### On this page [Resources](https://book.arch.network/docs/help-resources/resources#resources) [Bitcoin Mempool and Blockchain Explorer](https://book.arch.network/docs/help-resources/resources#bitcoin-mempool-and-blockchain-explorer) [Arch Regtest Explorer](https://book.arch.network/docs/help-resources/resources#arch-regtest-explorer) [General Bitcoin Resources](https://book.arch.network/docs/help-resources/resources#general-bitcoin-resources) [Development Tools](https://book.arch.network/docs/help-resources/resources#development-tools) [Solana Development](https://book.arch.network/docs/help-resources/resources#solana-development) [Rust Development](https://book.arch.network/docs/help-resources/resources#rust-development) [Arch Network Resources](https://book.arch.network/docs/help-resources/resources#arch-network-resources) [Official Repositories](https://book.arch.network/docs/help-resources/resources#official-repositories) [Community Resources](https://book.arch.network/docs/help-resources/resources#community-resources) [Bitcoin Development Resources](https://book.arch.network/docs/help-resources/resources#bitcoin-development-resources) [Bitcoin Core](https://book.arch.network/docs/help-resources/resources#bitcoin-core) [Bitcoin Libraries](https://book.arch.network/docs/help-resources/resources#bitcoin-libraries) [Cryptographic Resources](https://book.arch.network/docs/help-resources/resources#cryptographic-resources) [Threshold Signatures](https://book.arch.network/docs/help-resources/resources#threshold-signatures) [Schnorr Signatures](https://book.arch.network/docs/help-resources/resources#schnorr-signatures) [Development Environment](https://book.arch.network/docs/help-resources/resources#development-environment) [Docker Resources](https://book.arch.network/docs/help-resources/resources#docker-resources) [IDE and Editor Extensions](https://book.arch.network/docs/help-resources/resources#ide-and-editor-extensions) [VS Code Extensions](https://book.arch.network/docs/help-resources/resources#vs-code-extensions) [Other Editors](https://book.arch.network/docs/help-resources/resources#other-editors) [Testing and Debugging](https://book.arch.network/docs/help-resources/resources#testing-and-debugging) [Testing Frameworks](https://book.arch.network/docs/help-resources/resources#testing-frameworks) [Debugging Tools](https://book.arch.network/docs/help-resources/resources#debugging-tools) [Security Resources](https://book.arch.network/docs/help-resources/resources#security-resources) [Security Best Practices](https://book.arch.network/docs/help-resources/resources#security-best-practices) [Auditing Tools](https://book.arch.network/docs/help-resources/resources#auditing-tools) [Learning Resources](https://book.arch.network/docs/help-resources/resources#learning-resources) [Online Courses](https://book.arch.network/docs/help-resources/resources#online-courses) [Books](https://book.arch.network/docs/help-resources/resources#books) [Community and Support](https://book.arch.network/docs/help-resources/resources#community-and-support) [Forums and Communities](https://book.arch.network/docs/help-resources/resources#forums-and-communities) [News and Updates](https://book.arch.network/docs/help-resources/resources#news-and-updates) [Need More Help?](https://book.arch.network/docs/help-resources/resources#need-more-help) --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- --- # 404: This page could not be found. 404 === This page could not be found. ----------------------------- ---