Ethereum Wallet

Here is an example of the simple wallet.

πŸ’“ If you enjoyed the information and the web site, please donate or become a Patreon.

🌍 Love to travel? Check out Booking.com for all your travel needs.


πŸ“² Technologies Used

  • MetaMask which is your in-browser wallet that you will use to interact with your wallet.
  • Node.js is the programming language we are using to build this.
  • React a framework to create your website.
  • Chakra UI to design a clean web site.
  • Ethers.js to help you talk to the blockchain.

What is an ENS?

  • ENS stands for Ethereum Name Service, think of it as DNS but for ethereum addresses.
    • For example:
    • DNS: domain.com -> 192.420.666.69
    • ENS: ensname.eth -> 0x0000000000000000000000000000000000000000

πŸ’Ή Join Robinhood with my link and we will both pick a free stock.


πŸ“š Project Setup And Installation

  • Install MetaMask which is your in-browser wallet that you will use to interact with this.

  • Install Node.js if you have not already.

  • Go to your terminal and run the following commands to initialize your local server:

yarn create react-app simplewallet
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4
npm i ethers

After installing those dependencies you can start the project:

yarn start

🧠 Never forget any of your passwords with Roboform


πŸ’Ή Create Files And Your Wallet

Open the src/App.js file, this is the file that contains the code for your entire page. This is the only place you will update code for this project. Update your code to:

import { Button, Flex, Text } from '@chakra-ui/react';

function App() {
  const connectWallet = async () => {
    // we will try to connect to a wallet here
  }

  return (
    <Flex
      alignItems='center'
      justifyContent='center'
      height='100vh'
      bg='#6E304B'
    >
        <Button onClick={connectWallet}>Connect Wallet</Button>
    </Flex>
  );
}

export default App;
  • Also check to see if your index.js file updated to:
import React from 'react';
import ReactDOM from 'react-dom';
import { ChakraProvider } from '@chakra-ui/react'

import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <ChakraProvider>
      <App />
    </ChakraProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

You are importing Button and Flex from Chakra UI, this applies styles to Flex to center the Button in the center of the page. You also import Text as you will use that later on.

The onClick handler on your Button will call connectWallet function every time a user clicks on it.

There is nothing there right now in the function so nothing will happen if you click on it. Add a console.log(‘Please connect.’) inside the function and you should see things happening in the Developer console. Please Connect

You now have the base app and a function that is called anytime a user clicks the button.

  • Next is the use of ethers.js which is a library that will help you get information from the blockchain.

  • Import this at the top of your App.js file:

import { ethers } from 'ethers';
  • Update your connectWallet function to connect to the blockchain:
const connectWallet = async () => {
    if (!window.ethereum) {
      alert('🚨 Please install MetaMask.');
      return;
    }

  try {
    await window.ethereum.request({ method: 'eth_requestAccounts' });

    const provider =  new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const address = await signer.getAddress();

    console.log('address', address)
  } catch (error) {
    console.log(error)
  }
}

πŸ”’ Grab yourself a secure hardware wallet from Trezor


πŸ‘“ Review The Code

  • Here you are checking to see if a user has access to Ethereum in the browser. MetaMask inputs the Ethereum object in your browser and that is what is used to talk to the blockchain. If window.ethereum does not exist this means the user does not have Metamask installed and the user will not be able to display any information.
if (!window.ethereum) {
alert('Please install MetaMask.');
return;
}
  • Once the ethereum object exists in the browser, the user can connect to the wallet by calling the method eth_requestAccounts. This will open the MetaMask window asking the user for permission to read their accounts. Once the user authorizes the connection, the app can read and display the user’s address.
await window.ethereum.request({ method: 'eth_requestAccounts' });
  • To read information from the blockchain, the user needs to connect to it. The provider connects the app to a node (or multiple) so the app can query information.
const provider =  new ethers.providers.Web3Provider(window.ethereum);
  • The signer is the account connected to MetaMask. When provider.getSigner() is used, the app is getting the current connected account.
const signer = provider.getSigner();
  • Once access to the connected account is given, the app can get the address by await signer.getAddress().
const address = await signer.getAddress();

Here are a few resources to read about the technologies used:

πŸ‘₯ Learn a language with me for free through Duolingo


πŸ‘€ Display ENS

  • Import useState from React at the top of App.js. This is needed to store state and to update the component when the state changes. Once the address is stored, the button should be hidden to show the wallet address:
import { useState } from 'react';
  • Create an account object that will be stored in your component’s state. The initial state will be an empty object {} as the user needs to connect first. Put this above const connectWallet = async () => {:
const [account, setAccount] = useState({});

To show the connected address to the user, in the connectWallet function under const address = await signer.getAddress(); add two lines that will retrieve the account’s ENS name and avatar:

const ens = await provider.lookupAddress(address);
const avatar = await provider.getAvatar(ens);

The app is asking the provider to lookup the ENS address and avatar and it will return the ENS name and avatar if there is anything created for the ENS address and avatar.

  • Once the app obtains the address, the ENS, and the avatar, the app can store this information in the components state created earlier which is inside the account object. Put this under const avatar = await provider.getAvatar(ens);:
setAccount({
  address,
  avatar,
  ens
});
  • Here is how your file should look now:
import { Button, Flex, Text } from '@chakra-ui/react';
import { ethers } from 'ethers';
import { useState } from 'react';

function App() {
  const [account, setAccount] = useState({});

  const connectWallet = async () => {
    if (!window.ethereum) {
      alert('🚨 Please install Metamask.');
      return;
    }

    try {
      await window.ethereum.request({ method: 'eth_requestAccounts' });

      const provider =  new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const address = await signer.getAddress();
      const ens = await provider.lookupAddress(address);
      const avatar = await provider.getAvatar(ens);

      setAccount({
        address,
        avatar,
        ens
      });
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <Flex
      alignItems='center'
      justifyContent='center'
      height='100vh'
      bg='#6E304B'
    >
      <Button onClick={connectWallet}>πŸ”“ Connect Wallet</Button>
    </Flex>
  );
}

export default App;
  • If you click the button and connect your MetaMask wallet, nothing happens yet so add this code:
<Flex
  alignItems='center'
  justifyContent='center'
  height='100vh'
  bg='#6E304B'
>
  {account.address ? (
    <Text color='white'>{account.address}</Text>
  ) : (
    <Button onClick={connectWallet}>πŸ”“ Connect Wallet</Button>
  )}
</Flex>
  • You should now see your connected address instead of the button. The app is storing the ENS name and avatar with this code:
import { Avatar, Box, Button, Flex,  Text  } from '@chakra-ui/react';
import { ethers } from 'ethers';
import { useState } from 'react';

const shortenAddress = (address) => {
  return `${address.slice(0, 4)}...${address.slice(
    address.length - 4,
    address.length
  )}`;
}

function App() {
  const [account, setAccount] = useState({});

  const connectWallet = async () => {
    if (!window.ethereum) {
      alert('🚨 Please install MetaMask.');
      return;
    }

    try {
      await window.ethereum.request({ method: 'eth_requestAccounts' });

      const provider =  new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const address = await signer.getAddress();
      const ens = await provider.lookupAddress(address);
      const avatar = await provider.getAvatar(ens);

      setAccount({
        address,
        avatar,
        ens
      });
    } catch (error) {
      console.log(error)
    }
  }

  return (
    <Flex
      alignItems='center'
      justifyContent='center'
      height='100vh'
      bg='#6E304B'
    >
      {account.address ? (
        <Box
          maxW='sm'
          borderRadius='3xl'
          p='5'
          bg='white'
          textAlign='center'
        >
          <Avatar name={account.ens} src={account.avatar} size='lg' mb='2'  />
          {account.ens && (
            <Text fontSize='xl'>{account.ens}</Text>
          )}
          <Text fontSize='xs' title={account.address}>{shortenAddress(account.address)}</Text>
        </Box>
      ) : (
        <Button onClick={connectWallet}>πŸ”“ Connect Wallet</Button>
      )}
    </Flex>
  );
}

export default App;

πŸ”Ά Summary

  • asked permission to read from an account
  • communicated with a provider
  • retrieved and showed the account’s address
  • looked for any ENS information attached to that account

Here is an example of the simple wallet.

πŸ’“ If you enjoyed the information and the web site, please donate.

πŸ’Ά Earn Bitcoin by viewing ads at CoinPayU


Elyse Y. Robinson Elyse Y. Robinson is the Founder of Switch Into Tech where she does monthly seminars, posts weekly freebies to help you switch into tech, Writer of Nube: Switch Into A Cloud Career, podcaster for Nobody Wants To Work Tho, creator of FullTuitionScholarships.org to help you not go into college debt, and in school for Data Science. Elyse is in love with Mexico, researching any and everything, and helping people switch into tech.