Skip to content

Transaction

Ethereum

To send a transaction from the embedded wallet, send an eth_sendTransaction JSON-RPC request to the wallet provider. In the request's params, specify your transaction data as a hexadecimal string encoding of your transaction request.

By default, embedded wallets are connected to the Ethereum mainnet. To send a transaction on a different network, simply set the wallet's chainId in the transaction request.

Before calling this method, be sure to check the embeddedWalletState is connected.

swift
func sendTransaction() async throws {
    guard case .connected(let wallets) = privy.embeddedWallet.embeddedWalletState else {
        print("Wallet not connected")
        return
    }

    guard let wallet = wallets.first, wallet.chainType == .ethereum else {
        print("No Ethereum wallets available")
        return
    }

    let tx = try JSONEncoder().encode([
        "value": toHexString(100000000000000), // use a wei value in hex format
        "to": "0x52a4f8E69A12C36EF43d23DfA4d13D9c3bCae844", // destination address
        "chainId": "0xaa36a7", // Sepolia chainId as hex, defaults to mainnet (1) if omitted
        "from": wallet.address, // logged in user's embedded wallet address
    ])

    guard let txString = String(data: tx, encoding: .utf8) else {
        print("Data parse error")
        return
    }

    // Get RPC provider for wallet
    let provider = try privy.embeddedWallet.getEthereumProvider(for: wallet.address)

    let transactionHash = try await provider.request(
        RpcRequest(
            method: "eth_sendTransaction",
            params: [txString]
        )
    )

    print(transactionHash)
}