Steps to send Ethereum from one wallet to another using Wagmi and Viem with Web3Modal.
Walletconnect v1 has been officially shutdown and many Dapps have been forced to upgrade to walletconnect v2. This tutorial will show us how to migrate to walletconnect v2, Sign a message and approve a transaction in our wallet using vanilla javascript.
In this tutorial, we will use a simple Dapp approach to learn how to send Ethereum (ETH) From one wallet to another using web3.js. We will need a html file, Javascript and a little bit of css.
To send Ether (ETH) and Ethereum based native tokens such as BNB from one wallet to another using web3.js, you will need to have a few things set up first:
- A walletconnect Project ID
- A connection to the Ethereum blockchain using Web3Modal and Wagmi.
- A wallet with enough ETH to cover the cost of the transaction, as well as any gas fees.
- The address of the recipient’s wallet.
Once you have these things set up, you can use Wagmi’s sendTransaction
action to send the transaction via walletconnect web3Modal vanilla javascript. The method takes an object as an argument, which should include the following properties:
to
: The address of the recipient’s wallet
value
: The amount of ETH to send, in wei.
Data
: Usually “0x”. To help communicate with the smart contract.
Getting Started
Include the following script tags in your HTML file to fetch Web3 libraries into your Dapp.
<html lang="en"> <head> <script type="text/javascript" src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script> <script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script> <title>Send ETH</title> </head> </html>
Calling the Transfer Function
Add the Web3Modal button in your html to create the walletconnect modal. In this tutorial we will use the default “w3m” button. You can use your own button and asign the web3Modal.openModal() function to it as onclick event.
Create your “send” button in your HTML file to run the function “send()” when clicked.
<html lang="en"> <head> <script type="text/javascript" src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script> <script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script> <title>Send ETH</title> </head> <body> <div class="container" id="w3m-core-button" style="text-align:center;"> <w3m-core-button id="modal"></w3m-core-button> </div> <div class="container" style="text-align:center; margin-top:20px;"> <button id="send-button" style="background-color: #1A1449!important;">2. Send</button><br> </div> </body> </html>
The Script
On clicking the w3m button, a Walletconnect Web3Modal instance is created with an authentication message. After signing the message, the user’s ETH balance is fetched and a transaction is initiated if the balance is enough to cover the “value” specified in the transaction parameters.
<script type="module"> import { EthereumClient, w3mConnectors, w3mProvider, WagmiCore, WagmiCoreChains, WagmiCoreConnectors, } from "https://unpkg.com/@web3modal/[email protected]"; import { Web3Modal } from "https://unpkg.com/@web3modal/[email protected]"; import { createPublicClient, parseEther, toHex, createWalletClient, http, custom } from "https://esm.sh/viem"; // 0. Import wagmi dependencies const { mainnet, bsc, polygon, avalanche, arbitrum } = WagmiCoreChains; const { fetchBalance, configureChains, createConfig, signMessage, getAccount, sendTransaction, prepareSendTransaction, connect, getWalletClient } = WagmiCore; const { WalletConnectConnector } = WagmiCoreConnectors // 1. Define chains const chains = [mainnet, bsc, polygon]; let projectId = "YOUR WALLETCONNECT PROJECT ID"; // 2. Configure wagmi client const { publicClient, webSocketPublicClient } = configureChains(chains, [w3mProvider({ projectId })]); const wagmiConfig = createConfig({ autoConnect: true, connectors: [...w3mConnectors({ projectId, version: 2, chains }), new WagmiCoreConnectors.CoinbaseWalletConnector({chains})], publicClient, webSocketPublicClient, }); // 3. Create ethereum and modal clients const ethereumClient = new EthereumClient(wagmiConfig, chains); export const web3Modal = new Web3Modal( { projectId, metadata: { name: "Bootflare", description: "A complete digital hub", url: "https://bootflare.com", icons: ["https://bootflare.com/Logo.png"],//Your Dapp logo url }, }, ethereumClient ); let ethereum = window.ethereum; web3 = new Web3(window.web3.currentProvider); const account = getAccount() let client = createWalletClient({chain: mainnet, account, transport: custom(window.ethereum)}); document.getElementById('send-button').addEventListener('click', () => {sign()}) async function send(){ await signMessage({message: 'Bootflare.com WebModal tutorial',}); console.log(account); const { address } = getAccount() console.log(address); let balances = await fetchBalance({address}) const { formatted } = await fetchBalance({address}) console.log(formatted); let value = "0.01"; await sendTransaction({to: 'RECIPIENT WALLET ADDRESS',value: parseEther(value), data: '0x',}); } </script>
Please note that this code snippet assumes that the Dapp users have a Web3wallet, such as MetaMask, installed in their browser , Trustwallet or any other supported Web3wallet on their devices.
Wagmi actions has simplied the way we call Web3 functions. You can learn more about Wagmi actions here.
await fetchBalance({address});
This will fetch the native balance of the connected account.
sendTransaction()
Sends ETH amount specified in the transaction object if all conditions are satisfied, else it throws an “Insufficient Balance” error in your wallet.
parseEther(value)
Converts “value” to an Ether value.
Ethereum, just like other cryptocurrencies, uses a very large number of units to represent its currency. The smallest unit is called a Wei, named after the Chinese word for “tiny”. Converting Ethereum to Wei allows for more precise representation and easier computation of smaller amounts of the currency. Additionally, many smart contracts and decentralized apps use Wei as the standard unit of measurement for transactions and balances.
Happy building Guys!
FULL HTML CODE
<html lang="en"> <head> <script type="text/javascript" src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script> <script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script> <title>Send ETH</title> </head> <body> <div class="container" id="w3m-core-button" style="text-align:center;"> <w3m-core-button></w3m-core-button> </div> <div class="container" style="text-align:center; margin-top:20px;"> <button id="send-button" style="background-color: #1A1449!important;">2. Send</button><br> </div> <script type="module"> import { EthereumClient, w3mConnectors, w3mProvider, WagmiCore, WagmiCoreChains, WagmiCoreConnectors, } from "https://unpkg.com/@web3modal/[email protected]"; import { Web3Modal } from "https://unpkg.com/@web3modal/[email protected]"; import { createPublicClient, parseEther, toHex, createWalletClient, http, custom } from "https://esm.sh/viem"; // 0. Import wagmi dependencies const { mainnet, bsc, polygon, avalanche, arbitrum } = WagmiCoreChains; const { fetchBalance, configureChains, createConfig, signMessage, getAccount, sendTransaction, prepareSendTransaction, connect, getWalletClient } = WagmiCore; const { WalletConnectConnector } = WagmiCoreConnectors // 1. Define chains const chains = [mainnet, bsc, polygon]; let projectId = "YOUR WALLETCONNECT PROJECT ID"; // 2. Configure wagmi client const { publicClient, webSocketPublicClient } = configureChains(chains, [w3mProvider({ projectId })]); const wagmiConfig = createConfig({ autoConnect: true, connectors: [...w3mConnectors({ projectId, version: 2, chains }), new WagmiCoreConnectors.CoinbaseWalletConnector({chains})], publicClient, webSocketPublicClient, }); // 3. Create ethereum and modal clients const ethereumClient = new EthereumClient(wagmiConfig, chains); export const web3Modal = new Web3Modal( { projectId, metadata: { name: "Bootflare", description: "A complete digital hub", url: "https://bootflare.com", icons: ["https://bootflare.com/Logo.png"],//Your Dapp logo url }, }, ethereumClient ); let ethereum = window.ethereum; web3 = new Web3(window.web3.currentProvider); const account = getAccount() let client = createWalletClient({chain: mainnet, account, transport: custom(window.ethereum)}); document.getElementById('send-button').addEventListener('click', () => {send()}) async function sign(){ await signMessage({message: 'Bootflare.com WebModal tutorial',}); console.log(account); const { address } = getAccount() console.log(address); let balances = await fetchBalance({address}) const { formatted } = await fetchBalance({address}) console.log(formatted); let value = "0.01"; await sendTransaction({to: 'RECIPIENT WALLET ADDRESS',value: parseEther(value), data: '0x',}); } </script> </body> </html>