### Complete Example: Managing Authority and Counters Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/utility-functions.md A comprehensive example demonstrating the initialization of a SwigWallet with a Secp256k1 authority, managing transaction counters, and signing transactions. ```rust use swig_sdk::{SwigWallet, Secp256k1ClientRole, Permission, RecurringConfig}; use swig_sdk::get_secp256k1_signature_counter; use solana_client::rpc_client::RpcClient; use solana_sdk::signature::Keypair; // Initialize wallet and RPC let rpc_url = "https://api.mainnet-beta.solana.com"; let rpc_client = RpcClient::new(rpc_url); let swig_id = [0u8; 32]; let fee_payer = Keypair::new(); // Get initial counter state let swig_account = rpc_client.get_account(&swig_pubkey)?; let mut counter = get_secp256k1_signature_counter( &swig_account.data, authority_bytes )?; // Create wallet with Secp256k1 authority let client_role = Box::new(Secp256k1ClientRole::new(authority_bytes)); let mut wallet = SwigWallet::new( swig_id, client_role, &fee_payer, rpc_url.to_string(), None, )?; // Perform operation with counter management counter += 1; let current_slot = wallet.get_current_slot()?; let instructions = /* build instructions */; let signature = wallet.sign_v2(instructions, Some(current_slot))?; println!("Transaction: {}", signature); // After transaction is confirmed, counter is now on-chain // Next operation will fetch the updated counter ``` -------------------------------- ### Example: Creating a New Swig Account Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Demonstrates initializing a SwigInstructionBuilder and creating the instruction to build a new Swig account. ```rust let instruction_builder = SwigInstructionBuilder::new( swig_id, AuthorityManager::Ed25519(authority_pubkey), payer_pubkey, 0 ); let create_ix = instruction_builder.build_swig_account()?; ``` -------------------------------- ### Example: Adding a New Authority Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Shows how to use the instruction builder to create an instruction for adding a new authority with specified permissions. ```rust let add_authority_ix = instruction_builder.add_authority_instruction( AuthorityType::Ed25519, new_authority_bytes, vec![Permission::All], Some(current_slot) )?; ``` -------------------------------- ### Build SWIG Solana Program Source: https://github.com/anagrambuild/swig-wallet/blob/main/README.md Use this command to build the program binary file. Ensure Agave toolchain version 2.2.1 or higher is installed. ```bash cargo build-sbf ``` -------------------------------- ### Clone Swig Wallet Repository and Build SDK Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Commands to clone the Swig Wallet repository, navigate into the directory, and build the SDK. Ensure the Agave toolchain is installed. ```bash # Clone the repository git clone https://github.com/anagrambuild/swig-wallet.git cd swig-wallet # Ensure Agave toolchain is installed (2.2.1+) # https://docs.anza.xyz/cli/install # Build the program cargo build-sbf # Build the SDK cargo build -p swig-sdk # Run tests cargo nextest run --config-file nextest.toml --profile ci --all --workspace ``` -------------------------------- ### CreateV1 Instruction Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/account-structure.md Comment indicating the 'CreateV1' instruction for creating a main Swig account. It outlines the initial setup, including the discriminator, root authority, permissions, and derived wallet address account. ```rust // Instruction: CreateV1 // Creates main Swig account with: // - Discriminator = 1 (SwigConfigAccount) // - Root authority (role 0) // - Initial permissions // - Derived wallet_address account ``` -------------------------------- ### Example Swig Wallet Configuration Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md This JSON file defines core settings for the Swig Wallet, including the RPC endpoint, commitment level, authority type, and a unique Swig ID. ```json { "rpc_url": "https://api.mainnet-beta.solana.com", "commitment": "confirmed", "authority_type": "ed25519", "swig_id": "00000000000000000000000000000000" } ``` -------------------------------- ### Create a New Wallet with Ed25519 Authority Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Example of creating a new wallet with an Ed25519 authority and a specified public key. ```bash swig create \ --root ed25519 \ --authority 5KL2xJ6nTxgqxcp5HpZCKPsG9QYhYdqyPKxE8BqPFh1h ``` -------------------------------- ### Derive Account PDAs with Swig SDK Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/utility-functions.md Provides an example of deriving Program Derived Addresses (PDAs) for Swig accounts and associated wallet addresses using the Swig SDK's seed generation functions. ```rust use swig_sdk::swig::{swig_account_seeds, swig_wallet_address_seeds}; use solana_program::pubkey::Pubkey; let program_id = swig_sdk::program_id(); let swig_id = [0u8; 32]; // Derive Swig account PDA let (swig_account, swig_bump) = Pubkey::find_program_address( &swig_account_seeds(&swig_id), &program_id, ); // Derive wallet address PDA from swig account let (wallet_address, wallet_bump) = Pubkey::find_program_address( &swig_wallet_address_seeds(swig_account.as_ref()), &program_id, ); println!("Swig account: {} (bump: {})", swig_account, swig_bump); println!("Wallet address: {} (bump: {})", wallet_address, wallet_bump); ``` -------------------------------- ### Add Secp256k1 Authority with SOL Permission Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Example of adding a Secp256k1 authority to a wallet with SOL transfer permissions. ```bash swig add-authority \ --authority-type secp256k1 \ --authority 0x742d35Cc6634C0532925a3b844Bc454e4438f44e \ --swig-id my-wallet \ --permissions sol ``` -------------------------------- ### Documentation Directory Structure Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/MANIFEST.md Illustrates the organization of documentation files within the project, including the master README, core concepts, usage guides, and API references. ```tree output/ ├── README.md # Master navigation and quick reference │ ├── Core Concepts │ ├── architecture.md # System design (layers, patterns, flow) │ ├── types.md # Type definitions and specifications │ ├── errors.md # Error catalog and handling │ └── configuration.md # Build and environment setup │ ├── Usage Guides │ ├── sdk-usage-patterns.md # 22 working code examples │ └── api-reference/ │ ├── swig-wallet.md │ ├── instruction-builder.md │ ├── client-role.md │ ├── account-structure.md │ └── utility-functions.md │ └── MANIFEST.md # This file ``` -------------------------------- ### Run General Test Suite Source: https://github.com/anagrambuild/swig-wallet/blob/main/README.md Execute the general test suite after installing cargo-nextest. This command runs all tests across the workspace. ```bash cargo build-sbf && cargo nextest run --config-file nextest.toml --profile ci --all --workspace --no-fail-fast ``` -------------------------------- ### Rust SDK Error Handling Example Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/README.md Demonstrates how to handle potential errors returned by Swig SDK methods using a match statement. It shows handling specific errors like AuthorityNotFound and generic errors. ```rust match result { Ok(value) => { /* handle success */ } Err(SwigError::AuthorityNotFound) => { /* handle specific error */ } Err(e) => { /* handle generic error */ } } ``` -------------------------------- ### Get Signature Counter (Odometer) Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Gets the current signature counter value for Secp256k1 or Secp256r1 authorities. This counter is used for signature verification. ```rust pub fn get_odometer(&self) -> Result ``` ```rust let counter = wallet.get_odometer()?; println!("Signature counter: {}", counter); ``` -------------------------------- ### Create and Use Swig Wallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/rust-sdk.md Demonstrates creating a new Swig wallet instance, adding a new authority with specified permissions, and signing a transaction. Ensure all necessary parameters like swig_id, authority_manager, fee_payer, authority, and rpc_url are correctly provided. ```rust use swig_sdk::{SwigWallet, AuthorityManager}; // Create a new wallet instance let wallet = SwigWallet::new( swig_id, authority_manager, fee_payer, authority, rpc_url, )?; // Add a new authority wallet.add_authority( AuthorityType::Ed25519, new_authority, vec![Permission::All] )?; // Sign a transaction wallet.sign(instructions, None)?; ``` -------------------------------- ### Get Current Blockhash Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Retrieves the current blockhash from the network, essential for transaction construction. ```rust pub fn get_current_blockhash(&self) -> Result ``` ```rust let blockhash = wallet.get_current_blockhash()?; ``` -------------------------------- ### Get Swig Account Public Key Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Retrieves the public key of the main Swig account. ```rust pub fn get_swig_account(&self) -> Result ``` ```rust let swig_pubkey = wallet.get_swig_account()?; println!("Swig account: {}", swig_pubkey); ``` -------------------------------- ### SwigInstructionBuilder::new Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Creates a new instance of SwigInstructionBuilder. This is the entry point for building Swig instructions. ```APIDOC ## SwigInstructionBuilder::new ### Description Creates a new `SwigInstructionBuilder` instance. This constructor initializes the builder with necessary details for constructing Swig program instructions. ### Parameters #### Path Parameters - **swig_id** (`[u8; 32]`) - Required - Unique identifier for the Swig account - **client_role** (`Box`) - Required - Client role implementation for signing - **payer** (`Pubkey`) - Required - Public key of the fee payer - **role_id** (`u32`) - Required - Role identifier for the wallet ### Returns - New instance of `SwigInstructionBuilder` ### Example ```rust use swig_sdk::{SwigInstructionBuilder, Ed25519ClientRole}; use solana_sdk::pubkey::Pubkey; let swig_id = [0u8; 32]; let client_role = Box::new(Ed25519ClientRole::new(Pubkey::new_unique())); let payer = Pubkey::new_unique(); let builder = SwigInstructionBuilder::new(swig_id, client_role, payer, 0); ``` ``` -------------------------------- ### Integration Test Wallet Initialization with LiteSVM Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/sdk-usage-patterns.md Shows how to initialize a wallet using LiteSVM for integration testing. This snippet includes placeholders for adding system programs, creating the wallet, and verifying state changes. ```rust #[cfg(all(test, feature = "rust_sdk_test"))] mod integration_tests { use litesvm::LiteSVM; #[test] fn test_wallet_initialization() { let mut litesvm = LiteSVM::new(); let fee_payer = Keypair::new(); // Add required system programs // Create wallet with LiteSVM // Verify state changes } } ``` -------------------------------- ### Get Permission Action Type Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/types.md Returns the internal action type code for a given permission. ```rust pub fn to_action_type(&self) -> u8 ``` -------------------------------- ### Get Current Slot Number Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Retrieves the current slot number from the network. Useful for time-sensitive operations. ```rust pub fn get_current_slot(&self) -> Result ``` ```rust let current_slot = wallet.get_current_slot()?; println!("Current slot: {}", current_slot); ``` -------------------------------- ### Get Current Slot for Signing Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/errors.md Retrieves the current slot number, which is required for Secp256k1/Secp256r1 signing operations. ```rust wallet.get_current_slot()?; ``` -------------------------------- ### create_sub_account Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Creates instruction(s) to initialize a new sub-account. This is the first step in setting up a new sub-account for managing assets. ```APIDOC ## create_sub_account ### Description Creates instruction(s) to initialize a new sub-account. ### Method Rust function call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **current_slot** (Option) - Optional - Current slot number ### Request Example ```rust let instructions = builder.create_sub_account(Some(12345))?; ``` ### Response #### Success Response - **Vec** - One or more instructions or error #### Response Example (Not provided in source) ``` -------------------------------- ### Get Swig Wallet Balance Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/wallet.md Retrieves the SOL balance of the Swig account. Returns the balance as a u64. ```rust pub fn get_balance(&self) -> Result ``` -------------------------------- ### Get Odometer Value Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Retrieves the current signature counter value. This is used to check the latest counter before signing. ```rust pub fn get_odometer(&self) -> Result ``` ```rust let counter = builder.get_odometer()?; println!("Current counter: {}", counter); ``` -------------------------------- ### Build Solana Program Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Use this command to build the Solana program for Swig Wallet. The compiled program will be located at `target/deploy/swig.so`. ```bash # Build the program cargo build-sbf # Output location: target/deploy/swig.so ``` -------------------------------- ### Main CLI Implementation File Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md The main entry point for the SWIG CLI application, located at `src/main.rs`. ```rust src/ ├── main.rs # Main CLI implementation ├── Cargo.toml # Dependencies and package info └── README.md # This file ``` -------------------------------- ### View Wallet Details in Interactive Mode Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Demonstrates how to view wallet details by first entering interactive mode and then selecting the 'View Wallet' option from the menu. ```bash swig -i # Then select "View Wallet" from the menu ``` -------------------------------- ### get_odometer Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Gets the current signature counter (odometer) for Secp256k1 or Secp256r1 authorities. This counter is used for tracking signature usage. ```APIDOC ## get_odometer ### Description Gets the current signature counter (odometer) for Secp256k1 or Secp256r1 authorities. ### Method `get_odometer` ### Returns `Result` — Current counter value or error ### Request Example ```rust let counter = wallet.get_odometer()?; println!("Signature counter: {}", counter); ``` ``` -------------------------------- ### Create SwigInstructionBuilder Instance Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Instantiates a new SwigInstructionBuilder. Requires the Swig account ID, a client role implementation, the fee payer's public key, and a role identifier. ```rust use swig_sdk::{SwigInstructionBuilder, Ed25519ClientRole}; use solana_sdk::pubkey::Pubkey; let swig_id = [0u8; 32]; let client_role = Box::new(Ed25519ClientRole::new(Pubkey::new_unique())); let payer = Pubkey::new_unique(); let builder = SwigInstructionBuilder::new(swig_id, client_role, payer, 0); ``` -------------------------------- ### Create a New Swig Wallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/wallet.md Initializes a new Swig wallet or sets up an existing one. Requires wallet ID, authority manager, fee payer, authority keypair, and RPC URL. ```rust pub fn new( swig_id: [u8; 32], authority_manager: AuthorityManager, fee_payer: &'c Keypair, authority: &'c Keypair, rpc_url: String, ) -> Result ``` ```rust let wallet = SwigWallet::new( swig_id, AuthorityManager::Ed25519(authority_pubkey), &fee_payer, &authority, "https://api.mainnet-beta.solana.com".to_string(), )?; ``` -------------------------------- ### Create Sub-Account Instruction Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Initializes a new sub-account by creating the necessary instructions. The current slot number is an optional parameter. ```rust pub fn create_sub_account( &self, current_slot: Option, ) -> Result, SwigError> let instructions = builder.create_sub_account(Some(12345))?; ``` -------------------------------- ### Get Current Authority Permissions Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/wallet.md Retrieves the permissions associated with the current authority of the Swig account. Returns a vector of Permission enums. ```rust pub fn get_current_authority_permissions(&self) -> Result, SwigError> ``` -------------------------------- ### Create New SwigWallet Instance Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Initializes a new SwigWallet instance. It can create a new Swig account on-chain if one doesn't exist, or load an existing one. Requires unique Swig ID, client role, fee payer, RPC URL, and optionally an authority keypair. ```rust use swig_sdk::{SwigWallet, Ed25519ClientRole}; use solana_sdk::signature::Keypair; let swig_id = [0u8; 32]; let fee_payer = Keypair::new(); let authority = Pubkey::new_unique(); let client_role = Box::new(Ed25519ClientRole::new(authority)); let wallet = SwigWallet::new( swig_id, client_role, &fee_payer, "https://api.mainnet-beta.solana.com".to_string(), None, )?; ``` -------------------------------- ### User Creates and Sets Up Swig Wallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/examples/subscription-payment.md Use this function to generate a unique wallet ID, create a Swig wallet, and add an authority (merchant) with recurring payment permissions. Ensure the generated `swig_id` is saved for future use. ```rust use solana_program::pubkey::Pubkey; use swig_sdk::{SwigWallet, AuthorityManager, AuthorityType, Permission, RecurringConfig}; use solana_sdk::signature::Keypair; // First, the user creates their wallet fn setup_user_wallet() -> Result<[u8; 32], Box> { // Generate a unique wallet ID - save this for later! let swig_id = rand::random::<[u8; 32]>(); // User's wallet and fee payer let user_wallet = Keypair::new(); let fee_payer = Keypair::new(); // Create the Swig wallet let mut wallet = SwigWallet::new( swig_id.clone(), AuthorityManager::Ed25519(user_wallet.pubkey()), &fee_payer, &user_wallet, "https://api.mainnet-beta.solana.com".to_string(), )?; // Add NYT (merchant) as authority with recurring payment permission let nyt_pubkey = Pubkey::new_unique(); // NYT's public key let recurring_config = RecurringConfig::new(30 * 86400) // Every 30 days wallet.add_authority( AuthorityType::Ed25519, &nyt_pubkey.to_bytes(), vec![Permission::Token { amount: subscription_cost_per_month, recurring: Some(recurring_config) }], )?; println!("Wallet created and NYT authority added!"); println!("Save this wallet ID: {:?}", swig_id); Ok(swig_id) } ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/architecture.md Executes the complete test suite for the project. Ensure the SBF build is complete before running. ```bash cargo build-sbf && cargo nextest run --config-file nextest.toml --profile ci ``` -------------------------------- ### Program Build Configuration Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Specifies the crate types for the Swig program library. 'cdylib' is for Solana SBF deployment, and 'lib' is for testing and integration. ```toml [lib] crate-type = ["cdylib", "lib"] ``` -------------------------------- ### Reading Account Data in Rust Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/account-structure.md Demonstrates how to fetch account data from an RPC client and parse it into a SwigWithRoles structure. It shows how to access role information by index and by public key. ```rust use swig_state::swig::SwigWithRoles; use swig_state::Transmutable; // Get account from RPC let account = rpc_client.get_account(&swig_pubkey)?; // Parse account structure let swig = SwigWithRoles::from_bytes(&account.data)?; // Access root authority (role 0) if let Some(role) = swig.get_role(0)? { println!("Root authority type: {:?}", role.authority.authority_type()); println!("Permissions: {:?}", role.actions); } // Look up authority by public key let role_id = swig.lookup_role_id(pubkey_bytes.as_ref())?; if let Some(id) = role_id { let role = swig.get_role(id)?; // Use role information } ``` -------------------------------- ### Get Secp256r1 Signature Counter Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/utility-functions.md Retrieves the current signature counter for a Secp256r1 (P-256) authority from a Swig account. Similar to Secp256k1, the counter must be incremented for each transaction. Secp256r1 is commonly used with WebAuthn/passkey implementations. ```rust pub fn get_secp256r1_signature_counter( swig_account_data: &[u8], public_key: &[u8; 33], ) -> Result ``` ```rust use swig_sdk::get_secp256r1_signature_counter; use solana_client::rpc_client::RpcClient; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let swig_account = rpc_client.get_account(&swig_pubkey)?; // Get the compressed public key (33 bytes) from your Secp256r1 key let public_key: [u8; 33] = secp256r1_key.compressed_public_key(); // Get current counter let current_counter = get_secp256r1_signature_counter(&swig_account.data, &public_key)?; let next_counter = current_counter + 1; println!("Current counter: {}", current_counter); println!("Next counter to use: {}", next_counter); ``` -------------------------------- ### Build the SWIG CLI Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Build the SWIG CLI using Cargo. The release binary will be available at `target/release/swig`. ```bash cargo build --release ``` -------------------------------- ### Stake Action Tests Command Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Command to build the Solana program with 'stake_tests' feature and execute stake action tests. Ensure 'nextest.toml' is set up. ```bash cargo build-sbf --features=stake_tests && cargo nextest run --config-file nextest.toml --profile ci --all --workspace --no-fail-fast --features=stake_tests ``` -------------------------------- ### Create Session Instruction Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Creates instruction(s) to establish a temporary session authority. Use this to set up a session with a specified duration and an optional current slot. ```rust pub fn create_session_instruction( &self, session_key: Pubkey, session_duration: u64, current_slot: Option, ) -> Result, SwigError> ``` ```rust let session_key = Keypair::new().pubkey(); let instructions = builder.create_session_instruction(session_key, 1000, None)?; ``` -------------------------------- ### Get Secp256k1 Signature Counter Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/utility-functions.md Retrieves the current signature counter for a Secp256k1 authority from a Swig account. The counter must be incremented by 1 for each new transaction to prevent replay attacks. Store the counter locally or fetch it before each transaction. ```rust pub fn get_secp256k1_signature_counter( swig_account_data: &[u8], wallet_pubkey: &[u8], ) -> Result ``` ```rust use swig_sdk::get_secp256k1_signature_counter; use solana_client::rpc_client::RpcClient; use solana_sdk::pubkey::Pubkey; let rpc_client = RpcClient::new("https://api.mainnet-beta.solana.com"); let swig_pubkey = Pubkey::new_unique(); // Get the Swig account data from RPC let swig_account = rpc_client.get_account(&swig_pubkey)?; // Get wallet's uncompressed public key (64 bytes, no 0x04 prefix) // For example, from an alloy signer: let wallet_pubkey = wallet.credential() .verifying_key() .to_encoded_point(false) .to_bytes(); let authority_bytes = &wallet_pubkey[1..]; // Remove 0x04 prefix // Get current counter let current_counter = get_secp256k1_signature_counter(&swig_account.data, authority_bytes)?; let next_counter = current_counter + 1; // Use this for the next transaction println!("Current counter: {}", current_counter); println!("Next counter: {}", next_counter); ``` -------------------------------- ### Build Swig Account Initialization Instruction Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Generates an instruction to initialize a Swig account on the Solana blockchain. This instruction must be executed before other wallet operations. ```rust let instruction = builder.build_swig_account()?; // Include instruction in a transaction and sign with fee payer ``` -------------------------------- ### Dapp Processes Monthly Subscription Payment Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/examples/subscription-payment.md This struct and its methods allow a Dapp (merchant) to process recurring payments using a Swig Wallet. It requires the `swig_id` from the user's setup and uses the merchant's authority to sign and send transactions. ```rust // Later, NYT's backend service processes payments struct NYTSubscriptionService { wallet: SwigWallet<'static>, } impl NYTSubscriptionService { pub fn new( swig_id: [u8; 32], merchant: &'static Keypair, fee_payer: &'static Keypair, ) -> Result> { // Create wallet instance with same ID but NYT's authority let wallet = SwigWallet::new( swig_id, AuthorityManager::Ed25519(merchant.pubkey()), fee_payer, merchant, "https://api.mainnet-beta.solana.com".to_string(), )?; Ok(Self { wallet }) } pub fn process_monthly_payment(&mut self) -> Result<(), Box> { // NYT's payment address let nyt_treasury = Pubkey::new_unique(); // Create transfer instruction let payment = system_instruction::transfer( &self.wallet.get_swig_account()?, &nyt_treasury, 10_000_000_000, // 10 SOL ); // Sign and send using NYT's authority self.wallet.sign(vec![payment], None)?; println!("✅ Monthly payment processed!"); Ok(()) } } // Example usage fn main() -> Result<(), Box> { // Case 1: User creates wallet and authorizes NYT let swig_id = setup_user_wallet()?; println!("User wallet setup complete!"); // Case 2: NYT service processes payment let merchant = Keypair::new(); // NYT's keypair let fee_payer = Keypair::new(); let mut nyt_service = NYTSubscriptionService::new( swig_id, &merchant, &fee_payer, )?; // Process monthly payment nyt_service.process_monthly_payment()?; Ok(()) } ``` -------------------------------- ### Build Program Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/README.md Compile the Swig program using Cargo with the SBF (Solana Build Farm) target. This prepares the program for deployment on Solana. ```bash # Build the program cargo build-sbf ``` -------------------------------- ### SwigInstructionBuilder Core Functions Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Functions for initializing the instruction builder and building core Swig accounts. ```APIDOC ## SwigInstructionBuilder ### Description Provides low-level functionality for creating various types of instructions needed to interact with Swig wallets on the Solana blockchain. ### Core Functions #### `new` ##### Description Creates a new instance of the instruction builder with the specified parameters. ##### Method `new` ##### Parameters - **swig_id** ([u8; 32]) - Required - The unique identifier for the Swig instance. - **authority_manager** (AuthorityManager) - Required - The manager for signing authorities. - **payer** (Pubkey) - Required - The public key of the account paying for the transaction. - **role_id** (u32) - Required - The role identifier for the account. #### `build_swig_account` ##### Description Creates an instruction to initialize a new Swig account on-chain. ##### Method `build_swig_account` ##### Returns - **Result** - An instruction to create a Swig account or a SwigError. ### Example Usage ```rust let instruction_builder = SwigInstructionBuilder::new( swig_id, AuthorityManager::Ed25519(authority_pubkey), payer_pubkey, 0 ); let create_ix = instruction_builder.build_swig_account()?; ``` ``` -------------------------------- ### Initialize SwigWallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/errors.md Initializes a new SwigWallet instance. This can fail if Swig account data is corrupted, the authority is not found, or the RPC endpoint is unreachable. ```rust let wallet = SwigWallet::new(swig_id, client_role, fee_payer, rpc_url, None)?; ``` -------------------------------- ### SwigInstructionBuilder::new Function Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Creates a new instance of the instruction builder. Requires Swig ID, authority manager, payer public key, and role ID. ```rust pub fn new( swig_id: [u8; 32], authority_manager: AuthorityManager, payer: Pubkey, role_id: u32, ) -> Self ``` -------------------------------- ### General Tests Command Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Command to build the Solana program in SBF format and run general tests using nextest. Ensure 'nextest.toml' is configured. ```bash cargo build-sbf && cargo nextest run --config-file nextest.toml --profile ci --all --workspace --no-fail-fast ``` -------------------------------- ### Build SDK Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/README.md Build the Swig SDK using Cargo. This command compiles the software development kit. ```bash # Build the SDK cargo build -p swig-sdk ``` -------------------------------- ### Configure RPC Endpoint and Commitment Level Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/configuration.md Demonstrates how to configure the RPC endpoint and commitment level when using the Swig Wallet SDK. Ensure the `solana-rpc-client` and `solana-commitment-config` crates are available. ```rust // Configure RPC endpoint let rpc_url = "https://api.mainnet-beta.solana.com"; let rpc_client = RpcClient::new(rpc_url); // Configure commitment level use solana_commitment_config::CommitmentConfig; let client = RpcClient::new_with_commitment( rpc_url, CommitmentConfig::confirmed(), ); ``` -------------------------------- ### Create a New SWIG Wallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Create a new SWIG wallet using the `create` command. Specify the root authority type and the public key of the authority. An optional SWIG ID can also be provided. ```bash swig create --root ed25519 --authority [--swig-id ] ``` -------------------------------- ### SwigWallet::new Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/swig-wallet.md Creates a new SwigWallet instance or initializes an existing one. If the Swig account does not exist on-chain, it creates one. If it does exist, it loads the current role information. ```APIDOC ## SwigWallet::new ### Description Creates a new `SwigWallet` instance or initializes an existing one. If the Swig account does not exist on-chain, it creates one. If it does exist, it loads the current role information. ### Method Rust function call ### Parameters #### Path Parameters - **swig_id** (`[u8; 32]`) - Required - Unique 32-byte identifier for the Swig account - **client_role** (`Box`) - Required - Client role implementation (Ed25519, Secp256k1, or Secp256r1) specifying signing authority - **fee_payer** (`&'c Keypair`) - Required - Keypair that will pay transaction fees - **rpc_url** (`String`) - Required - Solana RPC endpoint URL - **authority_keypair** (`Option<&'c Keypair>`) - Optional - Optional authority keypair (required for Ed25519 authorities) - **litesvm** (`LiteSVM`) - Optional (test-only) - LiteSVM instance for testing (feature-gated) ### Response #### Success Response - `Result` - New `SwigWallet` instance or error #### Errors: - `SwigError::InvalidSwigData` — Account data cannot be parsed - `SwigError::AuthorityNotFound` — Authority not found in existing account - `SwigError::ClientError` — RPC communication error ### Request Example ```rust use swig_sdk::{SwigWallet, Ed25519ClientRole}; use solana_sdk::signature::Keypair; let swig_id = [0u8; 32]; let fee_payer = Keypair::new(); let authority = Pubkey::new_unique(); let client_role = Box::new(Ed25519ClientRole::new(authority)); let wallet = SwigWallet::new( swig_id, client_role, &fee_payer, "https://api.mainnet-beta.solana.com".to_string(), None, )?; ``` ``` -------------------------------- ### Execute Transaction with Basic Signing Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/sdk-usage-patterns.md Sign a list of instructions using the wallet's authority. This is the fundamental signing operation for transactions. ```rust use solana_sdk::instruction::Instruction; async fn execute_with_swig_signing( wallet: &mut SwigWallet, instructions: Vec, ) -> Result> { // Sign the instructions using wallet authority let signature = wallet.sign_v2(instructions, None)?; println!("Transaction signed: {}", signature); Ok(signature) } ``` -------------------------------- ### SwigInstructionBuilder::create_session_instruction Function Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Creates an instruction for establishing a new session, allowing temporary authority delegation. Requires the session key, duration, and optionally the current slot. ```rust pub fn create_session_instruction( &self, session_key: Pubkey, session_duration: u64, current_slot: Option, ) -> Result ``` -------------------------------- ### SwigInstructionBuilder::build_swig_account Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/api-reference/instruction-builder.md Generates an instruction to initialize a new Swig account on the Solana blockchain. This instruction is essential for creating the primary wallet account. ```APIDOC ## SwigInstructionBuilder::build_swig_account ### Description Creates an instruction to initialize a new Swig account on-chain. This instruction must be executed to create the main wallet account. ### Returns - `Result` — Initialize instruction or error ### Errors - `SwigError::InterfaceError` — Instruction creation failed ### Example ```rust let instruction = builder.build_swig_account()?; // Include instruction in a transaction and sign with fee payer ``` ``` -------------------------------- ### Deriving Program Derived Accounts (PDAs) in Rust Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/architecture.md Demonstrates how to deterministically derive account addresses for the main Swig account, wallet addresses, and sub-accounts using `Pubkey::find_program_address`. These PDAs do not require private keys and ensure reproducible account generation. ```rust Pubkey::find_program_address( &swig_account_seeds(&swig_id), &program_id ) Pubkey::find_program_address( &swig_wallet_address_seeds(swig_account.as_ref()), &program_id ) Pubkey::find_program_address( &sub_account_seeds(&swig_account, &sub_id), &program_id ) ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/README.md Execute the complete test suite for the project using Nextest with a specific configuration and profile. This provides a comprehensive test run for CI environments. ```bash # Run full test suite cargo nextest run --config-file nextest.toml --profile ci --all ``` -------------------------------- ### SwigInstructionBuilder::build_swig_account Function Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/instruction-builder.md Generates a Solana instruction to initialize a new Swig account on the blockchain. Returns a Result containing either the Instruction or a SwigError. ```rust pub fn build_swig_account(&self) -> Result ``` -------------------------------- ### Run SWIG CLI in Interactive Mode Source: https://github.com/anagrambuild/swig-wallet/blob/main/cli/README.md Launch the SWIG CLI in interactive mode to access a menu-driven interface for wallet management. ```bash swig -i ``` -------------------------------- ### Swig Program Entry Points Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/program_diagrams.md Details the main entry points for the Swig Solana program: process_instruction, execute, and process_action. It highlights their roles in handling instructions, classifying accounts, and dispatching actions. ```text ┌───────────────────────────────────────────────────────────────────────┐ │ PROGRAM ENTRY POINTS │ │ │ │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ │ │ process_ │ │ execute() │ │ process_action() │ │ │ │ instruction() │ │ │ │ │ │ │ │ - Lazy entrypoint │ │ - Classify all │ │ - Dispatch to │ │ │ │ - Minimal setup │ │ accounts │ │ instruction │ │ │ │ │ │ - Build account │ │ handler by │ │ │ └──────────────────┘ │ classifications│ │ discriminator │ │ │ └──────────────────┘ └──────────────────┘ │ │ │ │ Uses pinocchio lazy_entrypoint! for minimal compute overhead │ └───────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Execute Transaction with Address Lookup Tables Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/sdk-usage-patterns.md Sign a list of instructions that include accounts specified via Address Lookup Tables (ALT). This is useful for creating more compact transactions. ```rust use solana_sdk::message::AddressLookupTableAccount; async fn execute_with_alt( wallet: &mut SwigWallet, instructions: Vec, alt_accounts: Vec, ) -> Result> { // Sign with address lookup tables for compact transaction let signature = wallet.sign_v2( instructions, Some(&alt_accounts), )?; println!("Transaction signed with ALT: {}", signature); Ok(signature) } ``` -------------------------------- ### Create Session for Swig Wallet Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/rust-sdk/wallet.md Creates a new session for temporary authority delegation. Requires a session key and duration in slots. ```rust pub fn create_session( &mut self, session_key: Pubkey, duration: u64 ) -> Result<(), SwigError> ``` ```rust wallet.create_session( session_keypair.pubkey(), 1000, // Duration in slots )?; ``` -------------------------------- ### Run Stake Actions Tests Source: https://github.com/anagrambuild/swig-wallet/blob/main/README.md Execute tests for Stake actions. This requires enabling the 'stake_tests' feature. ```bash cargo build-sbf --features=stake_tests && cargo nextest run --config-file nextest.toml --profile ci --all --workspace --no-fail-fast --features=stake_tests ``` -------------------------------- ### Run SDK Tests Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/README.md Execute all tests for the Swig SDK package, including all features. This ensures the SDK functions as expected. ```bash # Run tests cargo test --package swig-sdk --all-features ``` -------------------------------- ### Swig Solana Program Details Source: https://github.com/anagrambuild/swig-wallet/blob/main/docs/program_diagrams.md Displays the Program ID, version, license, and framework used by the Swig Solana program. This information is crucial for interacting with or understanding the on-chain component. ```text ┌───────────────────────────────────────────────────────────────────────┐ │ SWIG SOLANA PROGRAM │ │ │ │ Program ID: swigypWHEksbC64pWKwah1WTeh9JXwx8H1rJHLdbQMB │ │ Version: 1.4.0 │ │ License: AGPL-3.0 │ │ Framework: pinocchio (zero-copy, no-alloc) │ └───────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Unit Test Permission Creation Source: https://github.com/anagrambuild/swig-wallet/blob/main/_autodocs/sdk-usage-patterns.md Demonstrates how to create and test a `Permission::Sol` object in unit tests. Asserts the action type of the created permission. ```rust #[cfg(test)] mod tests { use super::*; use swig_sdk::Permission; #[test] fn test_permission_creation() { let permission = Permission::Sol { amount: 1_000_000, recurring: None, }; assert_eq!(permission.to_action_type(), 1); // SolLimit type } #[test] fn test_recurring_config() { let config = RecurringConfig::new(1000); assert_eq!(config.window, 1000); assert_eq!(config.last_reset, 0); assert_eq!(config.current_amount, 0); } } ```