> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dynamic.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# SVM SDK Complete Example

> Complete example demonstrating all available SVM SDK functions with real API usage patterns

## Overview

This comprehensive example demonstrates all available functions in the Dynamic SVM SDK, showing the actual API usage patterns and how to handle common operations.

## Complete Example Code

```typescript theme={"system"}
// Import statements
import { DynamicSvmWalletClient } from "@dynamic-labs-wallet/node-svm";
import {
  Connection,
  LAMPORTS_PER_SOL,
  PublicKey,
  SystemProgram,
  Transaction,
} from "@solana/web3.js";
import { ThresholdSignatureScheme } from "@dynamic-labs-wallet/node";
import fs from "fs";

// Initialize SVM client
export const authenticatedSvmClient = async () => {
  const client = new DynamicSvmWalletClient({
    environmentId: process.env.DYNAMIC_ENVIRONMENT_ID!,
  });

  await client.authenticateApiToken(process.env.DYNAMIC_AUTH_TOKEN!);
  return client;
};

// Example usage demonstrating all available functions
async function main() {
  try {
    console.log("🚀 Starting SVM Client Demo...\n");

    // Initialize the SVM client
    const svmClient = await authenticatedSvmClient();
    console.log("✅ SVM client authenticated successfully\n");

    // 1. Create a new SVM wallet
    console.log("📝 Creating new SVM wallet...");
    const svmWallet = await svmClient.createWalletAccount({
      thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO,
      onError: (error: Error) => {
        console.error("❌ SVM wallet creation error:", error);
      },
      backUpToDynamic: true,
    });

    console.log("✅ SVM wallet created:", svmWallet.accountAddress);
    console.log("externalServerKeyShares:", svmWallet.externalServerKeyShares);
    console.log("rawPublicKey:", svmWallet.rawPublicKey);

    // Save wallet info to file
    fs.writeFileSync("svmWallet.json", JSON.stringify(svmWallet, null, 2));
    console.log("💾 Wallet saved to svmWallet.json\n");

    // 2. Get wallet information
    console.log("🔍 Getting wallet details...");
    try {
      const walletDetails = await svmClient.getWallet({
        accountAddress: svmWallet.accountAddress,
      });
      console.log("✅ Wallet details retrieved:", walletDetails);
    } catch (error) {
      console.log("⚠️ Could not retrieve wallet details:", error);
    }

    // 3. Get all SVM wallets
    console.log("\n📋 Getting all SVM wallets...");
    try {
      const allWallets = await svmClient.getSvmWallets();
      console.log("✅ Found", allWallets.length, "SVM wallets");
    } catch (error) {
      console.log("⚠️ Could not retrieve all wallets:", error);
    }

    // 4. Sign a message
    console.log("\n✍️ Signing a message...");
    try {
      const message = "Hello, Solana! This is a test message from Dynamic SVM wallet.";
      const signedMessage = await svmClient.signMessage({
        accountAddress: svmWallet.accountAddress,
        message,
      });
      console.log("✅ Message signed successfully");
      console.log("Signature:", signedMessage);
    } catch (error) {
      console.log("⚠️ Message signing failed:", error instanceof Error ? error.message : String(error));
    }

    // 5. Sign a transaction (Solana transfer example)
    console.log("\n💸 Preparing Solana transaction...");
    const connection = new Connection("https://api.devnet.solana.com", "confirmed");

    try {
      const amountInSol = 0.001;
      const recipientAddress = "EukgLDgaWNQRLemZSHK8Wc9EGhPhbG3wL9a1mxa3LHg6";

      // Create transaction
      const transaction = new Transaction().add(
        SystemProgram.transfer({
          fromPubkey: new PublicKey(svmWallet.accountAddress),
          toPubkey: new PublicKey(recipientAddress),
          lamports: amountInSol * LAMPORTS_PER_SOL,
        })
      );

      // Get latest blockhash
      const { blockhash } = await connection.getLatestBlockhash();
      transaction.recentBlockhash = blockhash;
      transaction.feePayer = new PublicKey(svmWallet.accountAddress);

      console.log("📝 Transaction prepared, signing with SVM wallet...");

      // Sign the transaction — returns base58 Ed25519 signature (not the full signed tx)
      const signatureBase58 = await svmClient.signTransaction({
        walletMetadata: svmWalletMetadata,
        transaction,
      });

      // To broadcast: decode the signature and add it back to the transaction
      // import { decodeBase58, addSignatureToTransaction } from '@dynamic-labs-wallet/node-svm';
      // const signedTx = addSignatureToTransaction({ transaction, signature: decodeBase58(signatureBase58), signerPublicKey });
      // const txid = await connection.sendRawTransaction(signedTx.serialize());

      console.log("✅ Transaction signed successfully");
      console.log("Signature (base58):", signatureBase58);
    } catch (error) {
      console.log("⚠️ Transaction signing failed:", error instanceof Error ? error.message : String(error));
    }

    // 6. Import private key (if you have one)
    console.log("\n🔑 Testing private key import...");
    try {
      const importedWallet = await svmClient.importPrivateKey({
        privateKey: "your-private-key-here", // Replace with actual private key
        chainName: "SVM",
        thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO,
        backUpToDynamic: true,
        password: "test-password",
      });
      console.log("✅ Private key imported:", importedWallet.accountAddress);
    } catch (error) {
      console.log("ℹ️ Private key import skipped (no valid key provided)");
    }

    // 7. Export key information
    console.log("\n📤 Exporting key information...");
    try {
      const exportedKey = await svmClient.exportKey({
        accountAddress: svmWallet.accountAddress,
        chainName: "SVM",
      });
      console.log("✅ Key exported:", exportedKey);
    } catch (error) {
      console.log("ℹ️ Key export not available or requires additional setup");
    }

    // 8. Export private key
    console.log("\n🔓 Exporting private key...");
    try {
      const privateKey = await svmClient.exportPrivateKey({
        accountAddress: svmWallet.accountAddress,
      });
      console.log("✅ Private key exported:", privateKey);
    } catch (error) {
      console.log("ℹ️ Private key export not available or requires additional setup");
    }

    // 9. Test connection to Solana network
    console.log("\n🌐 Testing Solana network connection...");
    try {
      const balance = await connection.getBalance(new PublicKey(svmWallet.accountAddress));
      console.log("✅ Solana connection successful");
      console.log("Wallet balance:", balance / LAMPORTS_PER_SOL, "SOL");
    } catch (error) {
      console.log("ℹ️ Solana network connection test skipped");
    }

    console.log("\n🎉 SVM Client Demo completed successfully!");
    console.log("📁 Check svmWallet.json for wallet details");

    // Summary of what was accomplished
    console.log("\n📊 Demo Summary:");
    console.log("✅ Successfully completed:");
    console.log(`   • Created SVM wallet: ${svmWallet.accountAddress}`);
    console.log(`   • Raw public key: ${svmWallet.rawPublicKey}`);
    console.log(`   • External server key shares: ${svmWallet.externalServerKeyShares?.length || 0}`);
    console.log(`   • Solana network connection: Working`);

    // Try to get additional wallet details if available
    try {
      const walletDetails = await svmClient.getWallet({
        accountAddress: svmWallet.accountAddress,
      });
      console.log(`   • Wallet ID: ${walletDetails.walletId || "N/A"}`);
      console.log(`   • Threshold scheme: ${walletDetails.thresholdSignatureScheme || "N/A"}`);
      console.log(`   • Chain name: ${walletDetails.chainName || "N/A"}`);
    } catch (error) {
      console.log("   • Additional wallet details: Not available");
    }

  } catch (error) {
    console.error("❌ Error in SVM demo:", error);
  }
}

// Run the example
main();
```

## Key API Patterns

### 1. Wallet Creation

```typescript theme={"system"}
const wallet = await svmClient.createWalletAccount({
  thresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO,
  onError: (error: Error) => {
    console.error("Wallet creation error:", error);
  },
  backUpToDynamic: true,
});
```

### 2. Message Signing

```typescript theme={"system"}
const signature = await svmClient.signMessage({
  message: "Hello, Solana!",
  accountAddress: wallet.accountAddress,
});
```

### 3. Transaction Signing

```typescript theme={"system"}
// Returns base58 Ed25519 signature — decode and attach before broadcasting
const signatureBase58 = await svmClient.signTransaction({
  walletMetadata: walletMetadata,
  transaction: transaction,
});

// Full broadcast pattern:
import { decodeBase58, addSignatureToTransaction } from '@dynamic-labs-wallet/node-svm';
const signedTx = addSignatureToTransaction({
  transaction,
  signature: decodeBase58(signatureBase58),
  signerPublicKey: new PublicKey(walletMetadata.accountAddress),
});
const txid = await connection.sendRawTransaction(signedTx.serialize());
```

### 4. Wallet Retrieval

```typescript theme={"system"}
const walletDetails = await svmClient.getWallet({
  accountAddress: wallet.accountAddress,
});
```

### 5. Getting All Wallets

```typescript theme={"system"}
const allWallets = await svmClient.getSvmWallets();
```

## Available Functions

The SVM SDK provides the following main functions:

* **`createWalletAccount()`** - Create new SVM wallet
* **`importPrivateKey()`** - Import existing private key
* **`getWallet()`** - Get specific wallet details
* **`getSvmWallets()`** - Get all SVM wallets
* **`signMessage()`** - Sign messages
* **`signTransaction()`** - Sign transactions
* **`exportKey()`** - Export wallet key data
* **`exportPrivateKey()`** - Export private key

## Error Handling

Always implement proper error handling:

```typescript theme={"system"}
try {
  const result = await svmClient.someFunction(params);
  console.log("Operation successful:", result);
} catch (error) {
  console.error("Operation failed:", error instanceof Error ? error.message : String(error));
}
```

## Environment Setup

Make sure you have these environment variables:

```bash theme={"system"}
DYNAMIC_AUTH_TOKEN=your_auth_token_here
DYNAMIC_ENVIRONMENT_ID=your_environment_id_here
```

## Dependencies

Install required packages:

```bash theme={"system"}
bun add @dynamic-labs-wallet/node-svm @solana/web3.js @dynamic-labs-wallet/node
```

## Next Steps

* [Create SVM wallets](/node/svm/create-wallet)
* [Sign transactions](/node/svm/sign-transactions)
* [Sign messages](/node/svm/sign-messages)
* [Import private keys](/node/svm/import-private-keys)
