### Prerequisites for Devnet Setup Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md Before running any setup commands, you need to copy the example environment file and edit it with your specific keys. This ensures that your environment is correctly configured for the subsequent operations. ```bash cp .env.example .env # Edit .env with your keys ``` -------------------------------- ### Setup and Build Contra Project Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Commands to clone the Contra repository, install dependencies, build all components, and run tests. This is the initial setup for developers. ```bash git clone https://github.com/solana-foundation/contra.git cd contra # Install dependencies for all projects make install # Build all components make build # Run tests to verify setup make all-test ``` -------------------------------- ### Bug Reporting Steps Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Illustrates the steps to reproduce a bug, including starting a node and submitting a transaction. This is a simplified example for bug reporting. ```bash 1. Start Contra node 2. Submit transfer transaction 3. Observe error XYZ ``` -------------------------------- ### Install Dependencies Command Source: https://github.com/solana-foundation/contra/blob/main/README.md A make command to install all project dependencies for Contra. ```bash make install ``` -------------------------------- ### Rust Unit Test Example Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Demonstrates how to write a unit test in Rust. Unit tests should be placed in the same file as the implementation they are testing. This example shows the standard Arrange-Act-Assert pattern. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn my_test_function() { // Arrange let x = 1; let y = 2; // Act let result = x + y; // Assert assert_eq!(result, 3); } } ``` -------------------------------- ### Contra Build and Test Commands Source: https://github.com/solana-foundation/contra/blob/main/README.md Shell commands for setting up and testing the Contra project locally. Includes cloning the repository, installing dependencies, building all components, and running all tests. ```bash # Clone repository git clone https://github.com/solana-foundation/contra.git cd contra # Install dependencies make install # Build all components make build # Test all components make all-test ``` -------------------------------- ### Start Development Server with pnpm Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Starts the development server for the Contra Admin UI. The application will be accessible at http://localhost:5173. This command is used during development to see changes in real-time. ```bash pnpm run dev ``` -------------------------------- ### Rust Integration Test Example Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Provides an example of an integration test for the Solana Contra project written in Rust. Integration tests are typically placed in the `integration/tests/` directory. This example uses `tokio::test` for asynchronous testing and assumes the availability of `contra_test_utils`. ```rust // integration/tests/contra/test_transaction_flow.rs use contra_test_utils::*; #[tokio::test] async fn my_test_function() { // Arrange let environment = setup_test_environment().await; // Act let result = environment.test_function(); // Assert assert_eq!(result, EXPECTED_RESULT); } ``` -------------------------------- ### Create Instance Command Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command creates a new instance on the Solana devnet. It requires the devnet API endpoint and the path to the admin keypair file. ```bash cargo run --bin create_instance -- \ https://api.devnet.solana.com \ ./keypairs/admin.json ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Installs project dependencies using the pnpm package manager. This is a prerequisite for running the development server or building the project. ```bash cd admin-ui pnpm install ``` -------------------------------- ### Build and Test Commands Source: https://context7.com/solana-foundation/contra/llms.txt Commands for installing dependencies, building, testing, and deploying the Contra project. ```APIDOC ## Build and Test Commands ### Install Dependencies ```bash make install ``` ### Build Components ```bash # Build all components (programs + core + indexer) make build # Build for devnet deployment make build-devnet ``` ### Run Tests ```bash # Run all tests make all-test # Run only unit tests make unit-test # Run only integration tests make integration-test ``` ### Generate IDL and Clients ```bash make generate-idl make generate-clients ``` ### Deploy to Devnet ```bash # Deploy to devnet (requires funded deployer key) make deploy-devnet DEPLOYER_KEY=/path/to/deployer.json ``` ### Generate Coverage Reports ```bash make all-coverage make coverage-html ``` ``` -------------------------------- ### Modern Provider Stack Setup Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Illustrates the modern provider stack used in the Contra Admin UI for managing network and Solana connections. It utilizes ClusterProvider for network management and SolanaProvider for RPC and Wallet Standard integration. ```typescript // ClusterContext - Network management // SolanaProvider - RPC + Wallet Standard ``` -------------------------------- ### Allow Mint Command Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command allows a specific mint address for an instance on the Solana devnet. It requires the devnet API endpoint, the admin keypair, the instance ID, and the mint address to be allowed. ```bash cargo run --bin allow_mint -- \ https://api.devnet.solana.com \ ./keypairs/admin.json \ \ ``` -------------------------------- ### Conventional Commit Messages for Versioning Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits specification. This format helps automate versioning and changelog generation. ```bash # Features (minor version bump) git commit -m "feat(lib): add Token2022 support" git commit -m "feat(rpc): implement new signAndSend method" # Bug fixes (patch version bump) git commit -m "fix(cli): handle invalid keypair format" git commit -m "fix(rpc): validate transaction signatures" # Breaking changes (major version bump) git commit -m "feat(lib)!: change signer interface" git commit -m "feat: remove deprecated methods BREAKING CHANGE: removed getBalance method, use getAccountBalance instead" # Other types (patch version bump) git commit -m "chore(deps): update solana-sdk to 2.1.10" git commit -m "docs(readme): add installation instructions" git commit -m "refactor(lib): simplify token validation logic" ``` -------------------------------- ### Docker Compose Deployment Setup Source: https://context7.com/solana-foundation/contra/llms.txt Creates a `.env` file with environment variables required for the Docker Compose deployment of the Contra stack. This includes database credentials, ports for services, and configuration for signature verification and transaction batching. ```bash cat > .env << EOF POSTGRES_DB=contra POSTGRES_USER=contra POSTGRES_PASSWORD=secure_password POSTGRES_REPLICATION_USER=replicator POSTGRES_REPLICATION_PASSWORD=repl_password CONTRA_WRITE_PORT=8899 CONTRA_READ_PORT=8900 GATEWAY_PORT=8898 CONTRA_SIGVERIFY_QUEUE_SIZE=10000 CONTRA_SIGVERIFY_WORKERS=4 CONTRA_WRITE_MAX_CONNECTIONS=100 CONTRA_READ_MAX_CONNECTIONS=200 CONTRA_MAX_TX_PER_BATCH=1000 CONTRA_ADMIN_KEYS=YourOperatorPubkey... EOF ``` -------------------------------- ### Deposit Command (Solana to Contra) Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command facilitates depositing tokens from Solana to a Contra instance. It requires the devnet API endpoint, the user's keypair, the instance ID, the mint address, and the amount to deposit. ```bash cargo run --bin deposit -- \ https://api.devnet.solana.com \ ./keypairs/user.json \ \ \ ``` -------------------------------- ### Monitor Deposit Processing Logs Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command allows you to monitor the logs for deposit processing by the Contra operator on the Solana side. It uses Docker to stream the logs in real-time. ```bash docker logs -f contra-operator-solana ``` -------------------------------- ### Build and Test Commands - Make Source: https://context7.com/solana-foundation/contra/llms.txt Collection of `make` commands for managing the Contra project build and test processes. Includes commands for installing dependencies, building all components, running various test suites (unit, integration, all), generating client code, and building/deploying to devnet. ```bash # Install dependencies make install # Build all components (programs + core + indexer) make build # Run all tests make all-test # Run only unit tests make unit-test # Run only integration tests make integration-test # Generate IDL and clients make generate-idl make generate-clients # Build for devnet deployment make build-devnet # Deploy to devnet (requires funded deployer key) make deploy-devnet DEPLOYER_KEY=/path/to/deployer.json # Generate coverage reports make all-coverage make coverage-html ``` -------------------------------- ### Start Docker Services Source: https://context7.com/solana-foundation/contra/llms.txt Launches all Contra services defined in the `docker-compose.yml` file in detached mode. This includes PostgreSQL primary and replica, write node, read node, and gateway. Logs for specific services can be monitored using `docker-compose logs -f`. ```bash # Build and start all services docker-compose up -d # Services started: # - postgres-primary (port 5432) - Write DB # - postgres-replica (port 5433) - Read DB # - write-node (port 8899) - Transaction processing # - read-node (port 8900) - Query handling # - gateway (port 8898) - Request routing # Check logs docker-compose logs -f write-node ``` -------------------------------- ### Withdraw Command (Contra to Solana) Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command enables withdrawing tokens from a Contra instance back to Solana. It requires a local Solana validator endpoint, the user's keypair, the mint address, and the amount to withdraw. ```bash cargo run --bin withdraw -- \ http://localhost:8898 \ ./keypairs/user.json \ \ ``` -------------------------------- ### Monitor Withdrawal Processing Logs Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command enables monitoring the logs for withdrawal processing by the Contra operator. It uses Docker to stream the logs related to the Contra withdrawal process in real-time. ```bash docker logs -f contra-operator-contra ``` -------------------------------- ### Add Operator Command Source: https://github.com/solana-foundation/contra/blob/main/scripts/devnet/README.md This command adds an operator to a specified instance on the Solana devnet. You need to provide the devnet API endpoint, the admin keypair, the instance ID, and the operator's public key. ```bash cargo run --bin add_operator -- \ https://api.devnet.solana.com \ ./keypairs/admin.json \ \ ``` -------------------------------- ### Start Contra Gateway Source: https://context7.com/solana-foundation/contra/llms.txt Initiates the Contra Gateway service, which routes JSON-RPC requests. It directs `sendTransaction` requests to write nodes and other queries to read nodes. Configuration is done via environment variables specifying ports and node URLs. ```bash GATEWAY_PORT=8898 \ GATEWAY_WRITE_URL=http://write-node:8899 \ GATEWAY_READ_URL=http://read-node:8900 \ GATEWAY_CORS_ALLOWED_ORIGIN="*" \ ./contra-gateway ``` -------------------------------- ### Migrate from Wallet Adapter to Wallet Standard Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Shows the transition from using `@solana/wallet-adapter-react` hooks like `useWallet` to the new Wallet Standard integration, utilizing hooks like `useSolana` and `useWalletAddress` from custom providers. ```typescript // OLD import { useWallet } from '@solana/wallet-adapter-react'; const { publicKey, sendTransaction } = useWallet(); // NEW import { useSolana, useWalletAddress } from './providers/SolanaProvider'; const { wallets, connect } = useSolana(); const walletAddress = useWalletAddress(); ``` -------------------------------- ### Implement Transaction Signing with Solana SDK Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md This snippet demonstrates how to implement transaction signing using the modern Solana SDK, including creating a transaction message, setting the fee payer, lifetime, and instructions, then signing and sending it via Wallet Standard. It utilizes functional pipe composition for building the transaction. ```typescript import { pipe } from '@solana/functional'; import { createTransactionMessage, setTransactionMessageFeePayer, appendTransactionMessageInstructions, setTransactionMessageLifetimeUsingBlockhash } from '@solana/transaction-messages'; import { signAndSendTransactionMessageWithSigners } from '@solana/signers'; // Example pattern for implementing transactions const { value: latestBlockhash } = await rpc.getLatestBlockhash().send(); const transactionMessage = pipe( createTransactionMessage({ version: 0 }), tx => setTransactionMessageFeePayer(walletAddress, tx), tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx), tx => appendTransactionMessageInstructions([instruction], tx) ); // Sign and send via Wallet Standard const signedTx = await wallet.features['solana:signAndSendTransaction'].signAndSendTransaction({ transaction: transactionMessage }); ``` -------------------------------- ### Build Project for Production with pnpm Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Builds the Contra Admin UI for production deployment. The output will be placed in the 'dist/' directory, and the gzipped bundle size is reported to be 78.96 KB. ```bash pnpm run build ``` -------------------------------- ### getLatestBlockhash - Get Recent Blockhash Source: https://context7.com/solana-foundation/contra/llms.txt Returns the latest blockhash for transaction signing. This is useful for ensuring that transactions are signed with a recent and valid blockhash. ```APIDOC ## POST /getLatestBlockhash ### Description Returns the latest blockhash for transaction signing. ### Method POST ### Endpoint http://localhost:8899 ### Parameters #### Query Parameters None #### Request Body ```json { "jsonrpc": "2.0", "id": 1, "method": "getLatestBlockhash", "params": [{"commitment": "confirmed"}] } ``` ### Request Example ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "getLatestBlockhash", "params": [{"commitment": "confirmed"}] }' ``` ### Response #### Success Response (200) - **context** (object) - Slot information. - **value** (object) - Contains blockhash and lastValidBlockHeight. - **blockhash** (string) - The recent blockhash. - **lastValidBlockHeight** (number) - The last valid block height for the blockhash. #### Response Example ```json { "jsonrpc": "2.0", "result": { "context": {"slot": 12345}, "value": { "blockhash": "EkSnNWid2cvwEVnVx9aBq...", "lastValidBlockHeight": 12445 } }, "id": 1 } ``` ``` -------------------------------- ### Build All Programs Command Source: https://github.com/solana-foundation/contra/blob/main/README.md A make command to build all programs within the Contra project. ```bash make build ``` -------------------------------- ### Rust Logging with Tracing Macros Source: https://github.com/solana-foundation/contra/blob/main/CONTRIBUTING.md Demonstrates the correct usage of the `tracing` crate for logging in Rust, emphasizing direct imports and appropriate log levels. It shows good and bad practices. ```rust use tracing::{debug, error, info, warn, trace}; // GOOD: Direct imports info!("Starting sequencer with max_tx_per_batch: {}", max_tx_per_batch); error!("Failed to process transaction: {}", error); // BAD: Using tracing:: prefix tracing::info!("This is not preferred"); // BAD: Using println/eprintln println!("This will not work in production"); // Log Levels: // trace!() - Very detailed debugging information // debug!() - Debugging information for development // info!() - Informational messages about normal operation // warn!() - Warning messages for recoverable issues // error!() - Error messages for failures ``` -------------------------------- ### Docker Compose Deployment Source: https://context7.com/solana-foundation/contra/llms.txt Full stack deployment with write/read node separation and PostgreSQL replication. ```APIDOC ## Docker Compose Deployment ### Description Full stack deployment with write/read node separation and PostgreSQL replication. ### Create `.env` file Configure your environment variables in a `.env` file. ```bash cat > .env << EOF POSTGRES_DB=contra POSTGRES_USER=contra POSTGRES_PASSWORD=secure_password POSTGRES_REPLICATION_USER=replicator POSTGRES_REPLICATION_PASSWORD=repl_password CONTRA_WRITE_PORT=8899 CONTRA_READ_PORT=8900 GATEWAY_PORT=8898 CONTRA_SIGVERIFY_QUEUE_SIZE=10000 CONTRA_SIGVERIFY_WORKERS=4 CONTRA_WRITE_MAX_CONNECTIONS=100 CONTRA_READ_MAX_CONNECTIONS=200 CONTRA_MAX_TX_PER_BATCH=1000 CONTRA_ADMIN_KEYS=YourOperatorPubkey... EOF ``` ### Start Services Build and start all services using Docker Compose. ```bash docker-compose up -d ``` ### Services Started: - `postgres-primary` (port 5432) - Write DB - `postgres-replica` (port 5433) - Read DB - `write-node` (port 8899) - Transaction processing - `read-node` (port 8900) - Query handling - `gateway` (port 8898) - Request routing ### Check Logs ```bash docker-compose logs -f write-node ``` ``` -------------------------------- ### Get Latest Blockhash - Solana RPC Source: https://context7.com/solana-foundation/contra/llms.txt Retrieves the most recent blockhash required for signing transactions. This method is commonly used to ensure transactions are submitted with a current and valid blockhash. It requires a JSON-RPC request to a Solana RPC endpoint. ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "getLatestBlockhash", "params": [{"commitment": "confirmed"}] }' ``` -------------------------------- ### Modern Solana SDK Class Replacements Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Illustrates the shift from deprecated class-based constructors in older Solana Web3.js versions to the new functional approach in the modern Solana SDK. This includes replacing `PublicKey`, `Connection`, and `Transaction`. ```typescript // OLD new PublicKey(address) new Connection(endpoint) new Transaction() // NEW address(addressString) createSolanaRpc(endpoint) createTransactionMessage({ version: 0 }) ``` -------------------------------- ### Initialize Escrow Instance (TypeScript) Source: https://context7.com/solana-foundation/contra/llms.txt Creates a new escrow instance with a designated admin. Each instance is isolated with unique Program Derived Addresses (PDAs) for administrative control, token mints, and Merkle tree roots. This function requires the payer, admin, and instance seed keypairs, along with the instance PDA and its bump seed. ```typescript import { getCreateInstanceInstructionAsync, findInstancePda, CONTRA_ESCROW_PROGRAM_PROGRAM_ADDRESS, } from '@contra/escrow-program'; import { generateKeyPairSigner } from '@solana/kit'; // Generate signers const payer = await generateKeyPairSigner(); const admin = await generateKeyPairSigner(); const instanceSeed = await generateKeyPairSigner(); // Get PDA and bump const [instancePda, bump] = await findInstancePda({ instanceSeed: instanceSeed.address, }); // Create the instruction const instruction = await getCreateInstanceInstructionAsync({ payer, admin, instanceSeed, bump, }); // Sign and send transaction // Program ID: GokvZqD2yP696rzNBNbQvcZ4VsLW7jNvFXU1kW9m7k83 ``` -------------------------------- ### Migrate from Node.js Buffer to Browser-Native APIs Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md This code demonstrates the migration from using Node.js's Buffer for base64 decoding to using browser-native APIs like `atob()`. This change eliminates the need for Node.js polyfills in browser environments. ```typescript // OLD (Node.js Buffer) const data = Buffer.from(base64, 'base64'); // NEW (Browser native) const binaryString = atob(base64); const data = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { data[i] = binaryString.charCodeAt(i); } ``` -------------------------------- ### Run Contra Indexer Source: https://context7.com/solana-foundation/contra/llms.txt Command to execute the Contra Indexer service. It requires a configuration file (e.g., `config.toml`) to be specified using the `--config` flag. The `RUST_LOG` environment variable can be set to control logging verbosity. ```bash RUST_LOG=info ./contra-indexer --config config.toml ``` -------------------------------- ### Configure Custom RPC Endpoint Source: https://github.com/solana-foundation/contra/blob/main/admin-ui/README.md Sets a custom RPC endpoint for the Contra Admin UI by creating a .env file. This allows users to connect to a specific Solana cluster or a custom RPC provider. ```env VITE_RPC_ENDPOINT=https://your-custom-rpc.com ``` -------------------------------- ### Query Token Balance (Bash) Source: https://context7.com/solana-foundation/contra/llms.txt Fetches the balance of a specific SPL token account. The response includes the token amount, its decimal places, and the UI representation of the amount. ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenAccountBalance", "params": ["TokenAccountPubkey..."] }' # Response: # { # "jsonrpc": "2.0", # "result": { # "context": {"slot": 12345}, # "value": { # "amount": "1000000", # "decimals": 6, # "uiAmount": 1.0, # } # } # } ``` -------------------------------- ### Indexer Configuration - TOML Source: https://context7.com/solana-foundation/contra/llms.txt Configuration file for the Contra Indexer, specifying program type, data source (RPC polling or Yellowstone gRPC), program ID, and connection details for RPC/gRPC endpoints and PostgreSQL. It also includes settings for operator functionality. ```toml # config.toml [indexer] program_type = "escrow" # or "withdraw" datasource = "rpc_polling" # or "yellowstone" program_id = "GokvZqD2yP696rzNBNbQvcZ4VsLW7jNvFXU1kW9m7k83" [indexer.rpc_polling] rpc_url = "https://api.mainnet-beta.solana.com" poll_interval_ms = 1000 start_slot = 0 [indexer.yellowstone] endpoint = "https://grpc.yellowstone.io" x_token = "your-token-here" [postgres] connection_url = "postgres://user:pass@localhost:5432/indexer" [operator] enabled = true rpc_url = "http://localhost:8899" keypair_path = "./keypairs/operator-keypair.json" ``` -------------------------------- ### ReleaseFunds - Withdraw from Escrow with SMT Proof Source: https://context7.com/solana-foundation/contra/llms.txt Releases tokens from escrow back to a user's wallet. Requires operator authorization and Sparse Merkle Tree proof verification to prevent double-spending. ```APIDOC ## ReleaseFunds - Withdraw from Escrow with SMT Proof ### Description Releases tokens from escrow back to a user's wallet. Requires operator authorization and Sparse Merkle Tree proof verification to prevent double-spending. ### Method POST (Implied by instruction creation) ### Endpoint N/A (Instruction-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Instruction parameters) ### Request Example ```typescript import { getReleaseFundsInstructionAsync } from '@contra/escrow-program'; const operator = await generateKeyPairSigner(); const amount = 500000n; // 0.5 USDC const userWallet = 'UserWalletAddress...'; const transactionNonce = 1n; // Unique nonce from channel // SMT proof data (generated by the operator/indexer) const newWithdrawalRoot = new Uint8Array(32); // New Merkle root after withdrawal const siblingProofs = new Uint8Array(512); // Merkle proof siblings const instruction = await getReleaseFundsInstructionAsync({ payer, operator, instance: instancePda, operatorPda, mint: usdcMint, user: userWallet, amount, newWithdrawalRoot, transactionNonce, siblingProofs, }); ``` ### Response #### Success Response (200) Instruction data for releasing funds. #### Response Example (Instruction data, not a direct JSON response) ``` -------------------------------- ### Release Funds from Escrow with SMT Proof (TypeScript) Source: https://context7.com/solana-foundation/contra/llms.txt Enables the release of tokens from escrow back to a user's wallet. This operation requires operator authorization and verification of a Sparse Merkle Tree (SMT) proof to ensure security and prevent double-spending. ```typescript import { getReleaseFundsInstructionAsync } from '@contra/escrow-program'; const operator = await generateKeyPairSigner(); const amount = 500000n; // 0.5 USDC const userWallet = 'UserWalletAddress...'; const transactionNonce = 1n; // Unique nonce from channel // SMT proof data (generated by the operator/indexer) const newWithdrawalRoot = new Uint8Array(32); // New Merkle root after withdrawal const siblingProofs = new Uint8Array(512); // Merkle proof siblings const instruction = await getReleaseFundsInstructionAsync({ payer, operator, instance: instancePda, operatorPda, mint: usdcMint, user: userWallet, amount, newWithdrawalRoot, transactionNonce, siblingProofs, }); ``` -------------------------------- ### Indexer Configuration Source: https://context7.com/solana-foundation/contra/llms.txt The Indexer monitors Solana Mainnet for deposits and the payment channel for withdrawals. Supports RPC polling or Yellowstone gRPC streaming. ```APIDOC ## Indexer Configuration ### Description The Indexer monitors Solana Mainnet for deposits and the payment channel for withdrawals. Supports RPC polling or Yellowstone gRPC streaming. ### Configuration File (`config.toml`) ```toml [indexer] program_type = "escrow" # or "withdraw" datasource = "rpc_polling" # or "yellowstone" program_id = "GokvZqD2yP696rzNBNbQvcZ4VsLW7jNvFXU1kW9m7k83" [indexer.rpc_polling] rpc_url = "https://api.mainnet-beta.solana.com" poll_interval_ms = 1000 start_slot = 0 [indexer.yellowstone] endpoint = "https://grpc.yellowstone.io" x_token = "your-token-here" [postgres] connection_url = "postgres://user:pass@localhost:5432/indexer" [operator] enabled = true rpc_url = "http://localhost:8899" keypair_path = "./keypairs/operator-keypair.json" ``` ### Running the Indexer ```bash RUST_LOG=info ./contra-indexer --config config.toml ``` ``` -------------------------------- ### Query Account State (Bash) Source: https://context7.com/solana-foundation/contra/llms.txt Retrieves detailed information about a specific account, including its balance (lamports), owner, data content, and other relevant state details. The query can specify the encoding and commitment level. ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "getAccountInfo", "params": [ "TokenAccountPubkeyHere...", { "encoding": "base64", "commitment": "confirmed" } ] }' # Response includes: lamports, owner, data, executable, rentEpoch ``` -------------------------------- ### Interact with Contra Gateway Source: https://context7.com/solana-foundation/contra/llms.txt Demonstrates how to send a JSON-RPC request to the running Contra Gateway. All RPC calls, including `getSlot`, are routed through the gateway, which then forwards them to the appropriate read or write node based on the method. ```bash curl -X POST http://localhost:8898 \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[]}' ``` -------------------------------- ### Simulate Transaction - Solana RPC Source: https://context7.com/solana-foundation/contra/llms.txt Allows simulation of a transaction before it is sent to the network, without consuming network resources. This helps in debugging and understanding the potential outcome of a transaction. It requires the transaction to be base64 encoded and specifies encoding and signature verification options. ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "simulateTransaction", "params": [ "BASE64_ENCODED_TRANSACTION", { "encoding": "base64", "sigVerify": true, "commitment": "confirmed" } ] }' ``` -------------------------------- ### Whitelist Token for Deposits (TypeScript) Source: https://context7.com/solana-foundation/contra/llms.txt Allows a specific SPL token mint to be used for deposits within an escrow instance. This operation can only be performed by the instance's admin. It requires the admin and payer signers, the instance PDA, the token mint address, and the PDA and bump seed for the allowed mint. ```typescript import { getAllowMintInstructionAsync, findAllowedMintPda, } from '@contra/escrow-program'; const admin = await generateKeyPairSigner(); const payer = await generateKeyPairSigner(); // USDC Mint address (example) const usdcMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; const [allowedMintPda, bump] = await findAllowedMintPda({ instance: instancePda, mint: usdcMint, }); const instruction = await getAllowMintInstructionAsync({ payer, admin, instance: instancePda, mint: usdcMint, bump, }); ``` -------------------------------- ### SetNewAdmin - Transfer Admin Rights Source: https://context7.com/solana-foundation/contra/llms.txt Transfers admin authority to a new account. Requires signatures from both current and new admin. ```APIDOC ## SetNewAdmin - Transfer Admin Rights ### Description Transfers admin authority to a new account. Requires signatures from both current and new admin. ### Method POST (Implied by instruction creation) ### Endpoint N/A (Instruction-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Instruction parameters) ### Request Example ```typescript import { getSetNewAdminInstructionAsync } from '@contra/escrow-program'; const currentAdmin = await generateKeyPairSigner(); const newAdmin = await generateKeyPairSigner(); const instruction = await getSetNewAdminInstructionAsync({ payer, currentAdmin, instance: instancePda, newAdmin, }); ``` ### Response #### Success Response (200) Instruction data for setting a new admin. #### Response Example (Instruction data, not a direct JSON response) ``` -------------------------------- ### Gateway Configuration Source: https://context7.com/solana-foundation/contra/llms.txt The Gateway routes JSON-RPC requests between write and read nodes based on method type. `sendTransaction` goes to write nodes; all other queries go to read nodes. ```APIDOC ## Gateway Configuration ### Description The Gateway routes JSON-RPC requests between write and read nodes based on method type. `sendTransaction` goes to write nodes; all other queries go to read nodes. ### Starting the Gateway Set the following environment variables and run the `contra-gateway` executable: - `GATEWAY_PORT`: The port the gateway will listen on. - `GATEWAY_WRITE_URL`: The URL of the write node. - `GATEWAY_READ_URL`: The URL of the read node. - `GATEWAY_CORS_ALLOWED_ORIGIN`: The CORS origin allowed for requests. ### Example Configuration ```bash GATEWAY_PORT=8898 \ GATEWAY_WRITE_URL=http://write-node:8899 \ GATEWAY_READ_URL=http://read-node:8900 \ GATEWAY_CORS_ALLOWED_ORIGIN="*" \ ./contra-gateway ``` ### Example Request All RPC calls go through the gateway. ```bash curl -X POST http://localhost:8898 \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"getSlot","params":[]}' ``` ``` -------------------------------- ### Transfer Admin Rights to New Account (TypeScript) Source: https://context7.com/solana-foundation/contra/llms.txt Facilitates the transfer of administrative control over the instance to a new account. This action requires the signatures of both the current and the designated new administrator. ```typescript import { getSetNewAdminInstructionAsync } from '@contra/escrow-program'; const currentAdmin = await generateKeyPairSigner(); const newAdmin = await generateKeyPairSigner(); const instruction = await getSetNewAdminInstructionAsync({ payer, currentAdmin, instance: instancePda, newAdmin, }); ``` -------------------------------- ### Withdrawal Flow Diagram Source: https://github.com/solana-foundation/contra/blob/main/README.md A Mermaid sequence diagram illustrating the withdrawal flow from a Contra payment channel, including privacy-preserving options such as batched settlement and confidential transfers. It shows interactions between Bob, the payment channel, the bank, Solana Mainnet, and Bob's wallet. ```mermaid sequenceDiagram participant Bob participant Channel as Contra Payment Channel participant Bank participant Mainnet as Solana Mainnet participant BobWallet as Bob's Wallet %% Initial State Note over Bob: Channel Balance: $31,000 TD %% Withdrawal Request Bob->>Channel: 1. Request $1,000 Withdrawal Channel->>Bank: 2. Process Withdrawal Bank->>Bank: 3. Compliance Check Bank-->>Channel: 4. Approved %% Privacy Options Note over Bank,Mainnet: PRIVACY OPTIONS alt Batched Settlement Bank->>Bank: 5a. Queue with other withdrawals Note over Bank: Aggregate:
Bob: $1,000
Alice: $500
Carol: $2,000 Bank->>Mainnet: 5b. Batch Settlement ($3,500) Mainnet->>Bank: 5c. Tokens Released Bank->>BobWallet: 5d. Distribute $1,000 TD Note right of BobWallet: No direct link
to channel account else Confidential Transfer (Token-2022) Bank->>Mainnet: 5a. Initiate Confidential Transfer Note over Mainnet: Amount encrypted
with ZK proof Mainnet->>BobWallet: 5b. Encrypted $1,000 TD BobWallet->>BobWallet: 5c. Decrypt with key Note right of BobWallet: Balance visible only
to Bob and Bank end Channel-->>Bob: 6. New Balance: $30,000 TD Channel->>Bank: 7. Log Withdrawal ``` -------------------------------- ### getAccountInfo - Query Account State Source: https://context7.com/solana-foundation/contra/llms.txt Retrieves account information including balance and data. ```APIDOC ## getAccountInfo - Query Account State ### Description Retrieves account information including balance and data. ### Method POST ### Endpoint `http://localhost:8899` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **jsonrpc** (string) - Must be "2.0". - **id** (integer) - Request ID. - **method** (string) - Must be "getAccountInfo". - **params** (array) - Array containing the account pubkey and options. - **params[0]** (string) - TokenAccountPubkeyHere... - **params[1]** (object) - Options. - **encoding** (string) - "base64". - **commitment** (string) - Commitment level (e.g., "confirmed"). ### Request Example ```bash curl -X POST http://localhost:8899 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "getAccountInfo", "params": [ "TokenAccountPubkeyHere...", { "encoding": "base64", "commitment": "confirmed" } ] }' ``` ### Response #### Success Response (200) - **jsonrpc** (string) - "2.0". - **result** (object) - Account information. - **context** (object) - Slot information. - **value** (object) - Account details. - **lamports** (number) - Amount of lamports. - **owner** (string) - Owner public key. - **data** (any) - Account data. - **executable** (boolean) - Whether the account is executable. - **rentEpoch** (integer) - Rent epoch. - **id** (integer) - Request ID. #### Response Example (Response structure depends on account type, includes lamports, owner, data, etc.) ``` -------------------------------- ### Deposit SPL Tokens into Escrow (TypeScript) Source: https://context7.com/solana-foundation/contra/llms.txt Allows any user to deposit SPL tokens into an escrow account for use within a payment channel. It requires the user's associated token account (ATA) for the specified mint and returns an instruction to be processed. ```typescript import { getDepositInstructionAsync } from '@contra/escrow-program'; import { findAssociatedTokenPda } from '@solana-program/token'; const user = await generateKeyPairSigner(); const amount = 1000000n; // 1 USDC (6 decimals) // Optional: specify a different recipient in the channel const recipient = 'RecipientPublicKeyInChannel...'; // or null for self // User's ATA for the mint const [userAta] = await findAssociatedTokenPda({ mint: usdcMint, owner: user.address, tokenProgram: TOKEN_PROGRAM_ADDRESS, }); const instruction = await getDepositInstructionAsync({ payer, user, instance: instancePda, mint: usdcMint, userAta, amount, recipient, // null = deposit to self }); ```