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

# Wallet Management Functions

<Note>
  This reference documents wallet management with the Dynamic Swift SDK. Wallets are automatically created for authenticated users. Access them via `sdk.wallets.userWallets` and observe changes using Combine publishers.
</Note>

## Accessing User Wallets

Wallets are automatically created for authenticated users. Access them via the SDK:

```swift theme={"system"}
let sdk = DynamicSDK.instance()

// Get all user wallets
let wallets = sdk.wallets.userWallets

// Observe wallet changes
sdk.wallets.userWalletsChanges
    .receive(on: DispatchQueue.main)
    .sink { wallets in
        print("User has \(wallets.count) wallet(s)")
    }
    .store(in: &cancellables)
```

### BaseWallet Properties

* **address** (String) - Wallet address
* **chain** (String) - Chain identifier (e.g., "EVM", "SOL")
* **walletName** (String?) - Optional wallet name
* **id** (String?) - Optional wallet ID

## sdk.wallets

Wallet management module for accessing and managing user wallets.

### userWallets

Get the current user's wallets.

```swift theme={"system"}
let wallets = sdk.wallets.userWallets  // [BaseWallet]
```

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

let wallets = sdk.wallets.userWallets

for wallet in wallets {
    print("Address: \(wallet.address)")
    print("Chain: \(wallet.chain)")
}
```

### userWalletsChanges

Combine publisher that emits when wallets change.

```swift theme={"system"}
sdk.wallets.userWalletsChanges  // Publisher<[BaseWallet], Never>
```

#### Example

```swift theme={"system"}
import Combine

let sdk = DynamicSDK.instance()
var cancellables = Set<AnyCancellable>()

sdk.wallets.userWalletsChanges
    .receive(on: DispatchQueue.main)
    .sink { wallets in
        print("Wallets updated: \(wallets.count) wallets")
        for wallet in wallets {
            print("  - \(wallet.chain): \(wallet.address)")
        }
    }
    .store(in: &cancellables)
```

### getBalance

Get the balance of a wallet.

```swift theme={"system"}
try await sdk.wallets.getBalance(wallet: BaseWallet) -> String
```

#### Parameters

* **wallet** (BaseWallet) - The wallet to get balance for

#### Returns

* **String** - The wallet balance

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

if let wallet = sdk.wallets.userWallets.first {
    do {
        let balance = try await sdk.wallets.getBalance(wallet: wallet)
        print("Balance: \(balance)")
    } catch {
        print("Failed to get balance: \(error)")
    }
}
```

### getNetwork

Get the current network of a wallet.

```swift theme={"system"}
try await sdk.wallets.getNetwork(wallet: BaseWallet) -> NetworkResult
```

#### Parameters

* **wallet** (BaseWallet) - The wallet to get network for

#### Returns

* **NetworkResult** - The current network information

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

if let wallet = sdk.wallets.userWallets.first {
    do {
        let network = try await sdk.wallets.getNetwork(wallet: wallet)
        print("Current network: \(network)")
    } catch {
        print("Failed to get network: \(error)")
    }
}
```

### switchNetwork

Switch a wallet to a different network.

```swift theme={"system"}
try await sdk.wallets.switchNetwork(wallet: BaseWallet, network: GenericNetwork)
```

#### Parameters

* **wallet** (BaseWallet) - The wallet to switch network for
* **network** (GenericNetwork) - The target network

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

if let wallet = sdk.wallets.userWallets.first,
   let targetNetwork = sdk.networks.evm.first {
    do {
        try await sdk.wallets.switchNetwork(wallet: wallet, network: targetNetwork)
        print("Switched to \(targetNetwork.name)")
    } catch {
        print("Failed to switch network: \(error)")
    }
}
```

### setPrimary

Set a wallet as the user's primary wallet.

```swift theme={"system"}
try await sdk.wallets.setPrimary(walletId: String)
```

#### Parameters

* **walletId** (String) - The ID of the wallet to set as primary

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

if let wallet = sdk.wallets.userWallets.first,
   let walletId = wallet.id {
    do {
        try await sdk.wallets.setPrimary(walletId: walletId)
        print("Primary wallet set successfully")
    } catch {
        print("Failed to set primary wallet: \(error)")
    }
}
```

### signMessage

Sign a message with a wallet.

```swift theme={"system"}
try await sdk.wallets.signMessage(wallet: BaseWallet, message: String) -> String
```

#### Parameters

* **wallet** (BaseWallet) - The wallet to sign with
* **message** (String) - The message to sign

#### Returns

* **String** - The signature

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

if let wallet = sdk.wallets.userWallets.first {
    do {
        let signature = try await sdk.wallets.signMessage(
            wallet: wallet,
            message: "Hello, World!"
        )
        print("Signature: \(signature)")
    } catch {
        print("Failed to sign message: \(error)")
    }
}
```

### signTypedData

Sign EIP-712 typed data with a wallet.

```swift theme={"system"}
try await sdk.wallets.signTypedData(wallet: BaseWallet, typedDataJson: String) -> String
```

#### Parameters

* **wallet** (BaseWallet) - The wallet to sign with
* **typedDataJson** (String) - The typed data as a JSON string

#### Returns

* **String** - The signature

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()

let typedData = """
{
    "types": {
        "EIP712Domain": [
            {"name": "name", "type": "string"},
            {"name": "version", "type": "string"},
            {"name": "chainId", "type": "uint256"}
        ],
        "Message": [
            {"name": "content", "type": "string"}
        ]
    },
    "primaryType": "Message",
    "domain": {
        "name": "Example",
        "version": "1",
        "chainId": 1
    },
    "message": {
        "content": "Hello!"
    }
}
"""

if let wallet = sdk.wallets.userWallets.first {
    do {
        let signature = try await sdk.wallets.signTypedData(
            wallet: wallet,
            typedDataJson: typedData
        )
        print("Signature: \(signature)")
    } catch {
        print("Failed to sign typed data: \(error)")
    }
}
```

### verifySignature

Verify a message signature.

```swift theme={"system"}
try await sdk.wallets.verifySignature(
    message: String,
    signature: String,
    walletAddress: String
) -> Bool
```

#### Parameters

* **message** (String) - Original message that was signed
* **signature** (String) - Signature to verify
* **walletAddress** (String) - Wallet address that signed the message

#### Returns

* **Bool** - True if signature is valid, false otherwise

#### Example

```swift theme={"system"}
let sdk = DynamicSDK.instance()
let message = "Hello There!"
let signature = "0x..." // Signature from signing step
let walletAddress = wallet.address

do {
    let verificationResult = try await sdk.wallets.verifySignature(
        message: message,
        signature: signature,
        walletAddress: walletAddress
    )

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

### checkKeySharesAvailability

Check if key shares are available for a wallet address.

```swift theme={"system"}
let hasKeyShares = checkKeySharesAvailability(
    client: dynamicClient,
    walletAddress: ethereumWallet.address.asString()
)

print("Key shares available: \(hasKeyShares)")
```

## Wallet Filtering

### Filter by Chain

```swift theme={"system"}
let sdk = DynamicSDK.instance()

// Get EVM wallets
let evmWallets = sdk.wallets.userWallets.filter {
    $0.chain.uppercased() == "EVM"
}

// Get Solana wallets
let solanaWallets = sdk.wallets.userWallets.filter {
    $0.chain.uppercased() == "SOL"
}
```

## Complete Wallet Management Example

```swift theme={"system"}
import SwiftUI
import DynamicSDKSwift
import Combine

@MainActor
class WalletViewModel: ObservableObject {
    @Published var wallets: [BaseWallet] = []
    @Published var selectedWallet: BaseWallet?
    @Published var balance: String?
    @Published var isLoading = false

    private let sdk = DynamicSDK.instance()
    private var cancellables = Set<AnyCancellable>()

    func startListening() {
        // Get current wallets
        wallets = sdk.wallets.userWallets
        selectedWallet = wallets.first

        // Listen for updates
        sdk.wallets.userWalletsChanges
            .receive(on: DispatchQueue.main)
            .sink { [weak self] newWallets in
                self?.wallets = newWallets
                if self?.selectedWallet == nil {
                    self?.selectedWallet = newWallets.first
                }
            }
            .store(in: &cancellables)
    }

    func refreshBalance() {
        guard let wallet = selectedWallet else { return }

        isLoading = true
        Task {
            do {
                balance = try await sdk.wallets.getBalance(wallet: wallet)
            } catch {
                print("Balance error: \(error)")
            }
            isLoading = false
        }
    }

    func signMessage(_ message: String) async -> String? {
        guard let wallet = selectedWallet else { return nil }

        do {
            return try await sdk.wallets.signMessage(wallet: wallet, message: message)
        } catch {
            print("Sign error: \(error)")
            return nil
        }
    }
}
```
