createWalletAccount

Create a new wallet account for an authenticated user.
public func createWalletAccount(client: DynamicClient) async throws -> String

Parameters

  • client (DynamicClient) - Initialized Dynamic client with authenticated user

Returns

  • String - The wallet address of the created wallet

Example

do {
    let accountAddress = try await createWalletAccount(client: dynamicClient)
    print("✅ Wallet created successfully!")
    print("Account Address: \(accountAddress)")
} catch {
    print("❌ Failed to create wallet: \(error)")
}

EthereumWallet

Ethereum wallet instance for managing wallet operations and transactions.
public class EthereumWallet {
    public let address: EthereumAddress
    public let accountAddress: BlockchainAddress

    public init(address: String, client: DynamicClient) throws
}

Initialization

public init(address: String, client: DynamicClient) throws

Parameters

  • address (String) - Ethereum wallet address
  • client (DynamicClient) - Initialized Dynamic client

Example

let walletAddress = "0x1234567890abcdef1234567890abcdef12345678"

do {
    let ethereumWallet = try EthereumWallet(
        address: walletAddress,
        client: dynamicClient
    )

    print("Wallet initialized: \(ethereumWallet.address.asString())")
} catch {
    print("Failed to initialize wallet: \(error)")
}

Properties

  • address (EthereumAddress) - Ethereum address object
  • accountAddress (BlockchainAddress) - Blockchain address for cross-chain compatibility

Methods

getBalance

Get the current balance of the wallet.
public func getBalance(_ block: BlockParameter) async throws -> BigUInt
Parameters
  • block (BlockParameter) - Block parameter (e.g., .Latest)
Returns
  • BigUInt - Balance in Wei
Example
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)")
}

signMessage

Sign a message with the wallet’s private key.
public func signMessage(_ message: String) async throws -> String
Parameters
  • message (String) - Message to sign
Returns
  • String - Signature in hex format
Example
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)")
}

sendTransaction

Send a transaction from the wallet.
public func sendTransaction(_ transaction: EthereumTransaction) async throws -> String
Parameters
  • transaction (EthereumTransaction) - Transaction to send
Returns
  • String - Transaction hash
Example
let transaction = EthereumTransaction(
    from: ethereumWallet.address,
    to: recipient,
    value: amount,
    data: Data(),
    nonce: nil,
    gasPrice: gasPrice,
    gasLimit: gasLimit,
    chainId: chainId
)

do {
    let txHash = try await ethereumWallet.sendTransaction(transaction)
    print("✅ Transaction sent!")
    print("🔗 Transaction Hash: \(txHash)")
} catch {
    print("❌ Transaction failed: \(error)")
}

switchNetwork

Switch the wallet to a different network.
public func switchNetwork(to network: ChainConfig) async throws
Parameters
  • network (ChainConfig) - Network configuration to switch to
Example
let sepoliaNetwork = SupportedEthereumNetwork.sepoliaTestnet.chainConfig

do {
    try await ethereumWallet.switchNetwork(to: sepoliaNetwork)
    print("🌐 Switched to Ethereum Sepolia")
} catch {
    print("❌ Failed to switch to Sepolia: \(error)")
}

getNetworkClient

Get a network client for a specific chain ID.
public func getNetworkClient(for chainId: BigUInt) async throws -> BaseEthereumClient
Parameters
  • chainId (BigUInt) - Chain ID of the network
Returns
  • BaseEthereumClient - Network client for the specified chain
Example
let chainId = SupportedEthereumNetwork.sepoliaTestnet.chainConfig.chainId

do {
    let networkClient: BaseEthereumClient = try await ethereumWallet.getNetworkClient(for: chainId)
    let gasPrice = try await networkClient.eth_gasPriceBigInt()
    print("Current gas price: \(gasPrice) wei")
} catch {
    print("Failed to get network client: \(error)")
}

exportPrivateKey

Export the wallet’s private key.
public func exportPrivateKey() async throws -> String
Returns
  • String - Private key in hex format
Example
do {
    let privateKey = try await ethereumWallet.exportPrivateKey()
    print("✅ Private key exported successfully!")
    print("🔑 Private Key: \(privateKey)")

    // Note: Store securely and clear from memory after use
} catch {
    print("❌ Failed to export private key: \(error)")
}

loadKeyShares

Load wallet key shares for an account address.
public func loadKeyShares(client: DynamicClient, accountAddress: String) -> KeyShares?

Parameters

  • client (DynamicClient) - Initialized Dynamic client
  • accountAddress (String) - Wallet account address

Returns

  • KeyShares? - Key shares if available, nil otherwise

Example

func checkKeySharesAvailability(client: DynamicClient, walletAddress: String) -> Bool {
    let keyShares = loadKeyShares(client: client, accountAddress: walletAddress)
    return keyShares != nil
}

let hasKeyShares = checkKeySharesAvailability(
    client: dynamicClient,
    walletAddress: ethereumWallet.address.asString()
)

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

verifySignature

Verify a message signature.
public func verifySignature(
    message: String,
    signature: String,
    walletAddress: String
) async throws -> 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

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

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

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

recoverEncryptedBackupByWallet

Recover encrypted backup for a wallet using key share IDs.
public func recoverEncryptedBackupByWallet(
    client: DynamicClient,
    walletId: String,
    keyShareIds: [Uuid],
    address: String
) async throws -> String

Parameters

  • client (DynamicClient) - Initialized Dynamic client
  • walletId (String) - Wallet ID
  • keyShareIds ([Uuid]) - Array of key share IDs
  • address (String) - Wallet address

Returns

  • String - Recovery result

Example

let walletId = credential.id
let keyShareIds = getKeyShareIds() // Get from credential properties

do {
    let backup = try await recoverEncryptedBackupByWallet(
        client: dynamicClient,
        walletId: walletId,
        keyShareIds: keyShareIds,
        address: ethereumWallet.address.asString()
    )

    print("✅ Keyshare recovered successfully!")
    print("Backup: \(backup)")
} catch {
    print("❌ Recovery failed: \(error)")
}

Wallet Initialization from Verified Credentials

Get wallet from user’s verified credentials.
// Get user's verified credentials and filter for blockchain wallets
if let verifiedCredentials = dynamicClient.user?.verifiedCredentials {
    for credential in verifiedCredentials {
        if credential.format == .blockchain,
           let walletAddress = credential.publicIdentifier {
            do {
                let wallet = try EthereumWallet(address: walletAddress, client: dynamicClient)
                print("Wallet found: \(wallet.address.asString())")
                break
            } catch {
                print("Failed to initialize wallet: \(error)")
            }
        }
    }
}

Key Share Management

Check Key Shares in Wallet Properties

func hasKeySharesInWaasProperties(credential: JwtVerifiedCredential) -> Bool {
    guard let walletProperties = credential.walletProperties,
          let waasProperties = walletProperties.value5,
          let keyShares = waasProperties.keyShares,
          !keyShares.isEmpty
    else {
        return false
    }
    return true
}

func getKeyShareIds(credential: JwtVerifiedCredential) -> [Uuid]? {
    guard let walletProperties = credential.walletProperties,
          let waasProperties = walletProperties.value5,
          let keyShares = waasProperties.keyShares
    else {
        return nil
    }

    return keyShares.map { $0.id }
}

Complete Key Share Recovery Example

private func recoverKeyshare(for credential: JwtVerifiedCredential) async {
    let walletId = credential.id

    guard let keyShareIds = getKeyShareIds(credential: credential) else {
        print("❌ No keyshare IDs found")
        return
    }

    do {
        let backup = try await recoverEncryptedBackupByWallet(
            client: dynamicClient,
            walletId: walletId,
            keyShareIds: keyShareIds,
            address: ethereumWallet.address.asString()
        )

        print("✅ Keyshare recovered successfully!")
        print("Backup: \(backup)")

        // Refresh key shares availability status
        await checkKeySharesAvailability()

    } catch {
        print("❌ Recovery failed: \(error)")
    }
}