/api/wallet/switch

GET

Switches the active wallet to a different wallet from the configured wallet list.

Description

The `/api/wallet/switch` endpoint changes which wallet is currently active. The active wallet is used for all coin operations (import, export, balance checks, etc.). The wallet is switched by swapping positions in the wallet list configuration - the first wallet in the list is always the active one.

💡 Active Wallet Behavior

All API endpoints that operate on coins (import, balance, export, etc.) will use the active wallet. Switching wallets allows you to work with different coin collections without needing to specify the wallet for each operation.

🔒 Security: Encryption Key Handling

When switching wallets, any encryption key currently loaded in memory may be cleared for security reasons. This prevents accidental use of one wallet's encryption key with another wallet's coins. You will need to re-enter the encryption key using /api/wallet/encryption/set after switching wallets if you need to access encrypted coins.

⚠️ Persistent Change

The wallet switch is saved to the wallet-locations.csv configuration file and persists across application restarts. The wallet must already exist in the wallet list (added via /api/wallet/add-location or /api/wallet/create) before it can be switched to.

🔤 Case Sensitivity

Wallet names are case-sensitive. "Savings" and "savings" are treated as different wallets. Ensure you use the exact wallet name as shown in /api/wallet/list.

Parameters

Parameter Type Required Description
name string Yes The name of the wallet to switch to (must exist in wallet list).

Response

Returns a JSON object confirming the wallet switch.

Response Properties

status string
Always "success" if the request was processed.
operation string
The operation type - "wallet-switch".
wallet string
The name of the newly activated wallet.
message string
A confirmation message.

Example Response (Success)

{
  "status": "success",
  "operation": "wallet-switch",
  "wallet": "Savings",
  "message": "Wallet switched successfully"
}

Example Error Response (Missing Parameter)

{
  "error": "Missing 'name' parameter"
}

Example Error Response (Wallet Not Found)

{
  "error": "Wallet not found"
}

Implementation Details

Understanding how wallet switching works internally can help you better integrate with the API:

Wallet List Configuration

The CloudCoin Console maintains a list of wallets in the wallet-locations.csv configuration file. The first wallet in this list is always considered the "active" wallet. When you switch wallets, the system:

  1. Searches for the target wallet in the list by name (case-sensitive exact match)
  2. Swaps the target wallet with the first wallet in the list
  3. Saves the updated configuration to wallet-locations.csv
  4. Returns success if the operation completes

Error Conditions

HTTP Status Error Cause
400 "Missing 'name' parameter" The name query parameter was not provided in the request
404 "Wallet not found" The specified wallet name does not exist in the wallet list
500 "Failed to save wallet configuration" The wallet was found but the configuration file could not be updated (permissions, disk full, etc.)

Configuration File Format

The wallet-locations.csv file has the following format:

Name,Location
Savings,C:\MyWallet3\Savings
Default,C:\MyWallet3\Default
Business,C:\MyWallet3\Business

The first row after the header is the active wallet. After switching to "Business", the file would be:

Name,Location
Business,C:\MyWallet3\Business
Default,C:\MyWallet3\Default
Savings,C:\MyWallet3\Savings

Examples

JavaScript (fetch)

const API_HOST = 'http://localhost:8080';

async function switchWallet(walletName) {
    try {
        const response = await fetch(
            `${API_HOST}/api/wallet/switch?name=${encodeURIComponent(walletName)}`
        );
        const result = await response.json();

        if (result.status === 'success') {
            console.log(`✓ Switched to wallet: ${result.wallet}`);
            console.log(`  ${result.message}`);
            return true;
        } else {
            console.error(`✗ Failed to switch wallet: ${result.error}`);
            return false;
        }
    } catch (error) {
        console.error('Error switching wallet:', error);
        return false;
    }
}

// Example: Switch to "Savings" wallet with verification
async function switchAndVerify(walletName) {
    console.log(`Switching to wallet: ${walletName}`);

    const success = await switchWallet(walletName);

    if (success) {
        // Verify the switch by checking program status
        const statusResponse = await fetch(`${API_HOST}/api/program/status`);
        const status = await statusResponse.json();
        console.log(`Active wallet is now: ${status.active_wallet}`);
    }
}

switchAndVerify('Savings');

cURL

# List all available wallets
curl -X GET "http://localhost:8080/api/wallet/list"

# Switch to "Savings" wallet
curl -X GET "http://localhost:8080/api/wallet/switch?name=Savings"

# Verify the switch by checking program status
curl -X GET "http://localhost:8080/api/program/status"

# Example with URL encoding for wallet names with spaces
curl -X GET "http://localhost:8080/api/wallet/switch?name=My%20Savings"

# Example error: wallet not found (404)
curl -X GET "http://localhost:8080/api/wallet/switch?name=NonExistent"
# Returns: {"error": "Wallet not found"}

# Example error: missing parameter (400)
curl -X GET "http://localhost:8080/api/wallet/switch"
# Returns: {"error": "Missing 'name' parameter"}

Go

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

const ApiHost = "http://localhost:8080"

type WalletSwitchResponse struct {
    Status    string `json:"status"`
    Operation string `json:"operation"`
    Wallet    string `json:"wallet"`
    Message   string `json:"message"`
    Error     string `json:"error,omitempty"`
}

type StatusResponse struct {
    Status       string `json:"status"`
    ActiveWallet string `json:"active_wallet"`
    WalletPath   string `json:"wallet_path"`
}

func switchWallet(walletName string) error {
    // Properly encode the wallet name for URL
    params := url.Values{}
    params.Add("name", walletName)

    requestURL := fmt.Sprintf("%s/api/wallet/switch?%s", ApiHost, params.Encode())

    resp, err := http.Get(requestURL)
    if err != nil {
        return fmt.Errorf("request failed: %w", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return fmt.Errorf("failed to read response: %w", err)
    }

    var result WalletSwitchResponse
    if err := json.Unmarshal(body, &result); err != nil {
        return fmt.Errorf("failed to parse response: %w", err)
    }

    if result.Error != "" {
        return fmt.Errorf("API error (%d): %s", resp.StatusCode, result.Error)
    }

    if result.Status == "success" {
        fmt.Printf("✓ Switched to wallet: %s\n", result.Wallet)
        fmt.Printf("  %s\n", result.Message)
        return nil
    }

    return fmt.Errorf("unexpected response status: %s", result.Status)
}

func verifyActiveWallet() (string, error) {
    resp, err := http.Get(fmt.Sprintf("%s/api/program/status", ApiHost))
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    var status StatusResponse
    if err := json.Unmarshal(body, &status); err != nil {
        return "", err
    }

    return status.ActiveWallet, nil
}

func main() {
    walletName := "Savings"

    fmt.Printf("Switching to wallet: %s\n", walletName)

    if err := switchWallet(walletName); err != nil {
        fmt.Printf("✗ Error: %v\n", err)
        return
    }

    // Verify the switch
    activeWallet, err := verifyActiveWallet()
    if err != nil {
        fmt.Printf("Warning: Failed to verify wallet switch: %v\n", err)
        return
    }

    fmt.Printf("Active wallet is now: %s\n", activeWallet)
}

Related Endpoints

/api/wallet/list

View all configured wallets to see which ones are available to switch to.

/api/wallet/create

Create a new wallet before switching to it.

/api/wallet/add-location

Add an existing wallet folder to the wallet list before switching to it.

/api/program/status

Verify which wallet is currently active after switching.