Overview

This guide covers basic wallet operations including balance management and message signing with the Dynamic Swift SDK.

Prerequisites

Balance Management

Get Wallet Balance

// Get latest balance
do {
    let balanceWei = try await ethereumWallet.getBalance(.Latest)

    // Convert Wei to Ether
    let etherValue = Double(String(balanceWei)) ?? 0.0
    let balanceEth = etherValue / pow(10.0, 18.0)

    print("Balance: \(String(format: "%.6f", balanceEth)) ETH")
} catch {
    print("Failed to get balance: \(error)")
}

Get Latest Balance and Convert to ETH

// Get latest balance (sample app usage)
do {
    let balanceWei = try await ethereumWallet.getBalance(.Latest)
    print("💰 Balance in Wei: \(balanceWei)")
    
    // Convert Wei to Ether (sample app conversion pattern)
    guard let etherValue = Double(String(balanceWei)) else {
        print("❌ Failed to convert balance to double")
        return
    }
    let etherInDecimals = etherValue / pow(10.0, 18.0)
    let balanceEth = String(format: "%.6f", etherInDecimals)
    
    print("💰 Balance in ETH: \(balanceEth)")
} catch {
    print("❌ Failed to fetch balance: \(error)")
}

Message Signing

Sign a Message

let message = "Hello There!"

do {
    let signature = try await ethereumWallet.signMessage(message)
    print("✅ Message signed successfully!")
    print("📝 Message: \(message)")
    print("🔏 Signature: \(signature)")
    print("🔏 Address: \(ethereumWallet.accountAddress.asString())")
} catch {
    print("❌ Failed to sign message: \(error)")
}

Verify Signature

import DynamicSwiftSDK

let message = "Hello There!"
let signature = "0x..." // Signature from signing step
let walletAddress = ethereumWallet.accountAddress.asString()

do {
    let verificationResult = try verifySignature(
        message: message,
        signature: signature,
        walletAddress: walletAddress
    )

    print("Verification Result: \(verificationResult)")
} catch {
    print("Failed to verify signature: \(error)")
}

Best Practices

1. Network Switching

Always switch to the desired network before performing operations:
// Switch to Sepolia first
let sepoliaNetwork = SupportedEthereumNetwork.sepoliaTestnet.chainConfig
try await wallet.switchNetwork(to: sepoliaNetwork)

// Then perform operations
let balance = try await wallet.getBalance(.Latest)

2. Balance Conversion

Use consistent conversion patterns for Wei to ETH:
// Standard conversion pattern
let etherValue = Double(String(balanceWei)) ?? 0.0
let balanceEth = etherValue / pow(10.0, 18.0)
let formattedBalance = String(format: "%.6f", balanceEth)

Next Steps

After mastering basic wallet operations, you can: