Course lesson
Retrieve Ethereum Network and Account information on Mount and Display it in Svelte
Now the UI is capable to connect to the Ethereum network by using the wallet, but we need two more things to continue.
- Duration
- 5 min
- Access
- Included
- Transcript
- Retained from source evidence
Now the UI is capable to connect to the Ethereum network by using the wallet, but we need two more things to continue.
- Avoid re-connecting every time the browser is refreshed
- Get more information about the user and the network.
For the first, let's run a little function every time the component is mounted.
Then, let's read and display some more information:
- The user balance
- The network that the user is currently connected
Important
SvelteKit is still in beta. Expect bugs! Read more here, and track progress towards 1.0 here.
This lesson was recorded before the latest breaking changes, the content is still valid but it sometimes references a file that does not exists anymore.
Now:
src/routes/index.svelte is called src/routes/+page.svelte
src/routes/__layout.svelte is called src/routes/+layout.svelte
Everything else is 100% valid. This particular content will be updated when Sveltekit reaches 1.0.0 stable.
Get network information
Now the UI is capable to connect to the Ethereum network by using the wallet, but we need two more things to continue.
- Avoid re-connecting every time the browser is refreshed
- Get more information about the user and the network.
For the first, let's run a little function every time the component is mounted.
onMount(async () => {
if (window.ethereum) {
const accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Just get the accounts but without permissions
if (accounts.length > 0) {
userAddress = accounts[0]; // Update the userAddress state variable
}
}
});Now, let's read some more information like:
- The user balance
- The network that the user is currently connected
Let's add this as state variables too
let network = null;
let balance = null;
let isConnected = false;
onMount(async () => {
if (window.ethereum) {
const accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Just get the accounts but without permissions
if (accounts.length > 0) {
userAddress = accounts[0]; // Update the userAddress state variable
const provider = new ethers.providers.Web3Provider(window.ethereum);
network = await provider.getNetwork();
balance = await provider.getBalance(userAddress);
isConnected = true;
}
}
});The only issue with this is that the same actions we added when the user re-load the page are required to be done when the user connect the wallet for the first time connectWallet function.
So we can extract this code to it's own function an reuse it.
async function connectWallet() {
if (window.ethereum) {
// ethereum is an object injected by the wallet. Let's check if is available
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); // use the request method to get the accounts, aka logging in to Metamask
if (accounts.length > 0) {
await setup(accounts);
} else {
alert('No ethereum accounts found');
}
} else {
alert('No ethereum Wallet found');
}
}
// Let's avoid clicking connect every time and check if the wallet was already connected
onMount(async () => {
if (window.ethereum) {
const accounts = await window.ethereum.request({ method: 'eth_accounts' }); // get the accounts
if (accounts.length > 0) {
await setup(accounts);
}
}
});
async function setup(accounts) {
userAddress = accounts[0]; // update the state
// Get and update the ethereum provider
const provider = new ethers.providers.Web3Provider(window.ethereum);
network = await provider.getNetwork();
balance = await provider.getBalance(userAddress);
isConnected = true;
}Now let's display the information in the HTML.
Here you'll show the network name and the current balance for the account. To do that you'll need to format the value (that comes like a BigNumber) into a readable number by using formatEther function from ethers.js utilities
{#if isConnected}
<p class="text-xl text-green-600">
Successfullly connected with account: <strong>{userAddress}</strong>
</p>
<ul>
<li>Current Network: {network.name}</li>
<li>Your current balance: {ethers.utils.formatEther(balance)} eth</li>
</ul>
{:else}
<button
class="bg-blue-600 text-gray-50 shadow-md rounded-md px-3 py-8 text-center"
on:click={connectWallet}>Connect with Wallet</button
>
{/if}You may be wondering why the different request methiods eth_accounts vs eth_requestAccounts
eth_requestAccountsThis request cause the wallet to popup to ask the user to allow the request. You should only request user's accounts in response to user actions like a button click.eth_accountsJust return the list of addresses owned by the client.