Klaytn 문서 아카이브
시작하기스마트 컨트랙트노드 운영dApp 개발자
  • Klaytn 문서
  • -
    • Klaytn Overview
      • 왜 클레이튼일까요?
      • 클레이튼 디자인
        • 합의 메커니즘
        • 계정
        • 트랜잭션
          • 기본
          • 수수료 위임 트랜잭션
          • 수수료 부분 위임 트랜잭션
          • Ethereum
        • 연산
          • 클레이튼 스마트 컨트랙트
          • 실행 모델(Execution Model)
          • Computation Cost
            • 연산 비용 (구 버전 문서)
          • Klaytn 가상머신
            • 클레이튼 가상머신 (구 버전 문서)
        • 스토리지
        • 트랜잭션 비용
          • 트랜잭션 비용 (구 버전 문서)
        • 클레이튼의 네이티브 코인 - KLAY
        • 토큰 이코노미
        • 거버넌스
        • 다중 채널
        • KNI
      • 확장성 솔루션
    • Getting Started
      • Deploying Smart Contract Using Foundry
      • Deploying Smart Contract Using Hardhat
      • Deploying Smart Contract Using KEN
        • Launch an Endpoint Node
        • Top up your Account
        • Install Development Tools
        • Deploy a Smart Contract
        • Check the Deployment
        • Account Management
          • Creating Accounts
          • Managing Accounts
      • Development Environment
      • Getting KLAY
    • 스마트 컨트랙트
      • 솔리디티 - 스마트 컨트랙트 언어
      • 미리 컴파일된 컨트랙트
        • 미리 컴파일된 컨트랙트 (구 버전 문서)
      • IDE 및 도구
        • Truffle
      • 샘플 컨트랙트
        • KlaytnGreeter
        • ERC-20
          • 1. ERC-20 스마트 컨트랙트 작성
          • 2. 스마트 컨트랙트 배포
          • 3. 클레이튼 월렛에서 ERC-20 토큰 사용
        • ERC-721
          • 1. ERC-721 스마트 컨트랙트 작성
          • 2. Deploying Smart Contract
      • 테스트 가이드
      • 배포 가이드
      • 클레이튼 호환 토큰
      • 이더리움 컨트랙트 이식
    • Run a Node
      • 배포
        • Endpoint Node
          • 시스템 요구사항
          • 설치 가이드
            • 다운로드
            • Installation Guide
            • 환경설정
            • EN 실행하기
            • 설치 테스트하기
          • ken CLI 명령어
          • JSON-RPC API
        • 코어 셀
          • System Requirements
          • 네트워크 설정
          • Installation Guide
            • Download
            • 설치하기 전에
            • 컨센서스 노드 설정
              • Installation Guide
              • Configuration
              • CN 실행하기
            • 프록시 노드 설정
              • Installation Guide
              • Configuration
              • PN 실행하기
            • 코어 셀 테스트하기
          • 모니터링 설정
          • H/A 설정
        • Service Chain
          • Getting Started
            • 4개 노드 서비스 체인 설정하기
            • Connecting to Baobab
            • 크로스체인 토큰 전송
            • HA(High Availability) for ServiceChain
            • Nested ServiceChain
            • Value Transfer between Sibling ServiceChains
          • 참조 매뉴얼
            • System Requirements
            • Download
            • SCN User Guide
              • Installation
              • Configuration
              • SCN 실행 및 중지하기
              • 노드 상태 확인하기
              • kscn commands
              • homi commands
            • SPN/SEN User Guide
              • Installation
              • Configuration
              • 노드 실행 및 중지
              • Checking Node Status
            • Bridge Configuration
            • 앵커링
            • KAS 앵커링
            • 토큰 전송
            • Configuration Files
            • 로그 파일
            • Genesis JSON
            • 업그레이드 및 하드포크
          • How-To Guides
        • Download Node Packages
          • v1.11.1
          • v1.11.0
          • v1.10.2
          • v1.10.1
          • v1.10.0
          • v1.9.1
          • v1.9.0
          • v1.8.4
          • v1.8.3
          • v1.8.2
          • v1.8.1
          • v1.8.0
          • v1.7.3
          • v1.7.2
          • v1.7.1
          • v1.7.0
          • v1.6.4
          • v1.6.3
          • v1.6.2
          • v1.6.1
          • v1.6.0
          • v1.5.3
          • v1.5.2
          • v1.5.1
          • v1.5.0
          • v1.4.2
          • v1.4.1
          • v1.4.0
          • v1.3.0
          • v1.2.0
          • v1.1.1
          • v1.0.0
          • v0.9.6
          • v0.8.2
    • 운영 가이드
      • Configuration
      • 노드 로그
      • Log operation
      • 에러 및 문제 해결
      • Klaytn Command
      • Chaindata Change
      • Chaindata Migration
    • dApp Developers
      • JSON-RPC APIs
        • API references
          • eth
            • Caution
            • Account
            • Block
            • Transaction
            • Config
            • Filter
            • Gas
            • Miscellaneous
          • klay
            • Account
            • Block
            • Transaction
              • Working with Klaytn Transaction Types
            • Configuration
            • Filter
            • Gas
            • Miscellaneous
          • net
          • debug
            • Logging
            • Profiling
            • Runtime Tracing
            • Runtime Debugging
            • VM Tracing
            • VM Standard Tracing
            • Blockchain Inspection
          • admin
          • personal
          • txpool
          • governance
        • Service Chain API references
          • mainbridge
          • subbridge
        • Transaction Error Codes
      • RPC Service Providers
        • Public Endpoints
      • SDK & Libraries for interacting with Klaytn Node
        • caver-js
          • Getting Started
          • Sending a sample transaction
          • API references
            • caver.account
            • caver.wallet
              • caver.wallet.keyring
            • caver.transaction
              • Basic
              • Fee Delegation
              • Partial Fee Delegation
            • caver.rpc
              • caver.rpc.klay
              • caver.rpc.net
              • caver.rpc.governance
            • caver.contract
            • caver.abi
            • caver.kct
              • caver.kct.kip7
              • caver.kct.kip17
              • caver.kct.kip37
            • caver.validator
            • caver.utils
            • caver.ipfs
          • caver-js ~v1.4.1
            • Getting Started (~v1.4.1)
            • API references
              • caver.klay
                • Account
                • Block
                • Transaction
                  • Legacy
                  • Value Transfer
                  • Value Transfer Memo
                  • Account Update
                  • Smart Contract Deploy
                  • Smart Contract Execution
                  • Cancel
                • Configuration
                • Filter
                • Miscellaneous
              • caver.klay.net
              • caver.klay.accounts
              • caver.klay.Contract
              • caver.klay.KIP7
              • caver.klay.KIP17
              • caver.klay.abi
              • caver.utils (~v1.4.1)
            • Porting from web3.js
        • caver-java
          • Getting Started
          • API references
          • caver-java ~v1.4.0
            • Getting Started (~v1.4.0)
            • Porting from web3j
        • ethers.js
        • web3.js
      • Tutorials
        • Klaytn Online Toolkit
        • Fee Delegation Example
        • Count DApp
          • 1. Environment Setup
          • 2. Clone Count DApp
          • 3. Directory Structure
          • 4. Write Smart Contract
          • 5. Frontend Code Overview
            • 5-1. Blocknumber Component
            • 5-2. Auth Component
            • 5-3. Count Component
          • 6. Deploy Contract
          • 7. Run App
        • Klaystagram
          • 1. Environment Setup
          • 2. Clone Klaystagram DApp
          • 3. Directory Structure
          • 4. Write Klaystagram Smart Contract
          • 5. Deploy Contract
          • 6. Frontend Code Overview
          • 7. FeedPage
            • 7-1. Connect Contract to Frontend
            • 7-2. UploadPhoto Component
            • 7-3. Feed Component
            • 7-4. TransferOwnership Component
          • 8. Run App
        • Building a Buy Me a Coffee dApp
          • 1. Project Setup
          • 2. Creating a BMC Smart Contract
          • 3. Testing the contract using scripts
          • 4. Deploying BMC Smart contract
          • 5. Building the BMC Frontend with React and Web3Onboard
          • 6. Deploying Frontend code on IPFS using Fleek
          • 7. Conclusion
        • Migrating Ethereum App to Klaytn
        • Connecting MetaMask
        • Connecting Remix
        • Verifying Smart Contracts Using Block Explorers
      • Developer Tools
        • Wallets
          • Kaikas
          • Klaytn Wallet
          • Klaytn Safe
            • Klaytn Safe Design
            • Create a Safe
            • Add assets
            • Send assets
            • Contract Interaction
            • Transaction Builder
            • Points to Note
            • Frequently Asked Questions
          • Wallet Libraries
            • Web3Auth
            • Web3Modal
            • Web3-Onboard
        • Oracles
          • Orakl Network
          • Witnet
          • SupraOracles
        • Block Explorers
          • Klaytnscope
          • Klaytnfinder
        • Klaytn Contracts Wizard
    • Glossary
  • ---
    • Klaytn 하드포크
    • 클레이튼 2.0
      • 메타버스 패키지
      • 완결성과 개선 사항들
      • 이더리움 호환성
      • 거버넌스 탈중앙화
      • 대규모 에코 펀드
    • FAQ
    • 오픈 소스
    • 이용약관
    • 지원 언어
  • ℹ️최신 Klaytn 문서
Powered by GitBook
On this page
  • 5.1 Setting up Web3Onboard Provider and Wallet Modules
  • Step 1 - Installing @web3-onboard/react
  • Step 2 - Installing and Instantiating Wallet Modules
  • Step 3 - Installing ethers
  • Step 4 - Instantiating Web3Onboard using the Web3OnboardProvider
  • Important notes from the code above

Was this helpful?

  1. -
  2. dApp Developers
  3. Tutorials
  4. Building a Buy Me a Coffee dApp

5. Building the BMC Frontend with React and Web3Onboard

Previous4. Deploying BMC Smart contractNext6. Deploying Frontend code on IPFS using Fleek

Last updated 1 year ago

Was this helpful?

In this section, we will be building our dApp frontend website with Next.js and Web3Onbaord. To get started, you have to navigate to the frontend folder previously created.

cd ..
cd frontend 

The next step is to install the necessary dependencies to get our BMC frontend website up and running. The following are the packages to be installed:

  1. Web3Onboard packages: Web3-Onboard is a chain-agnostic wallet library that supports multi-wallet compatibility in your dApp built on EVM-compatible networks like Klaytn Blockchain.

  2. ethers.js: Web3-Onboard provider can be used with libraries like and. In this guide, we will use ethers.js to make Klaytn blockchain calls like getting the user's account, fetch balance, sign transaction, send transaction, read from and write to the smart contract.

Important Note: We need to edit 2 files in the frontend/pages folder

  • _app.js

  • index.js

5.1 Setting up Web3Onboard Provider and Wallet Modules

Step 1 - Installing @web3-onboard/react

npm install @web3-onboard/react

In your _app.js file, import the web3OnboardProvider and init function. More to be discussed later.

import { Web3OnboardProvider, init } from '@web3-onboard/react'

Step 2 - Installing and Instantiating Wallet Modules

In this step, you can add as many wallets to be supported in your dApp using the wallet modules. But for this guide, you will add Coinbase Wallet, WalletConnect, Injected Wallets to your web3-Onboard implementation.

npm install @web3-onboard/coinbase // Coinbase Wallet
npm install @web3-onboard/walletconnect // WalletConnect
npm install @web3-onboard/injected-wallets  // Used to connect to Metamask

In your _app.js file, import and instantiate the wallet modules to integrate with your dApp. Note that each module has its own unique options parameters to pass in, such as a fallback JSON RPC URL or default chain ID.

import coinbaseWalletModule from "@web3-onboard/coinbase";
import walletConnectModule from "@web3-onboard/walletconnect";
import injectedModule from "@web3-onboard/injected-wallets";
const coinbaseWalletSdk = coinbaseWalletModule();
const walletConnect = walletConnectModule();
const injected = injectedModule();
const modules = [coinbaseWalletSdk, walletConnect, injected];

Step 3 - Installing ethers

npm install --save ethers

Step 4 - Instantiating Web3Onboard using the Web3OnboardProvider

Web3OnboardProvider provides a better way to manage global state. It simplifies wrapping the provider object around your App and the initialized Web3Onboard instance will be available in all children components.

Init function initializes web3-Onboard and makes it available for all hooks to use.

To see this in action, paste the code below the previous code in your _app.jsfile:

const ETH_MAINNET_RPC_URL = `https://ethereum-mainnet-rpc.allthatnode.com/1d322388ZEPI2cs0OHloJ6seI4Wfy36N`;
const KLAYTN_MAINNET_URL = `https://klaytn-mainnet-rpc.allthatnode.com:8551/1d322388ZEPI2cs0OHloJ6seI4Wfy36N`;
const KLAYTN_BAOBAB_URL = `https://klaytn-baobab-rpc.allthatnode.com:8551/1d322388ZEPI2cs0OHloJ6seI4Wfy36N`;
  const web3Onboard =  init({
    wallets: modules,
    chains: [
      {
        id: "0x1", // chain ID must be in hexadecimal
        token: "ETH",
        namespace: "evm",
        label: "Ethereum Mainnet",
        rpcUrl: ETH_MAINNET_RPC_URL
      },
      {
        id: "0x2019", // chain ID must be in hexadecimal
        token: "KLAY",
        namespace: "evm",
        label: "Klaytn Mainnet",
        rpcUrl: KLAYTN_MAINNET_URL
      },
      {
        id: "0x3e9", // chain ID must be in hexadecimel
        token: "KLAY",
        namespace: "evm",
        label: "Klaytn Testnet",
        rpcUrl: KLAYTN_BAOBAB_URL
      },
     // you can add as much supported chains as possible
    ],
    appMetadata: {
      name: "Klaytn-web3-onboard-App", // change to your dApp name
      icon: "paste your icon url"
      logo: "paste your logo url"
      description: "Web3Onboard-Klaytn",
      recommendedInjectedWallets: [
        { name: "Coinbase", url: "https://wallet.coinbase.com/" },
        { name: "MetaMask", url: "https://metamask.io" }
      ]
    }
  })
export default function App({ Component, pageProps }) {
  return (
    <Web3OnboardProvider web3Onboard={web3Onboard}>
      <Component {...pageProps} />
    </Web3OnboardProvider>
 )
}

Having set up our _app.js file which grants our App a provider object and web3Onboard instance available in all children components, next is to build out front-end logic in our index.js file

  • Index.js

This page handles wallet connection and sending of coffee to the BMC smart contract which is to be withdrawn by the contract deployer.

import React, { useEffect, useState } from 'react';
import { useConnectWallet } from '@web3-onboard/react'
import abi from "../utils/BuyMeACoffee.json"
import { ethers } from "ethers";

export default function Home() {
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");
  const [coffee, setGetCoffee] = useState([]);
  const [coffeeContract, setCoffeeContract] = useState();
  const [{ wallet, connecting }, connect, disconnect] = useConnectWallet();
  const contractAddress = "Paste BMC contract address";
  const contractABI = abi.abi;
  const getCoffee = async () => {
    try {
       console.log("getting coffee Id")
       const coffeeId = await coffeeContract.coffeeId();
       console.log(coffeeId.toString());
       const getCoffee = await coffeeContract.getAllCoffee(coffeeId.toString());
       setGetCoffee(getCoffee);
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    let ethersProvider
    if (wallet) {
       ethersProvider = new ethers.BrowserProvider(wallet.provider, 'any')
    }


    if (ethersProvider) {
      try {
        const getCoffeContract = async () => {
          const signer =  await ethersProvider.getSigner();

          const buyMeACoffee = new ethers.Contract(contractAddress, contractABI, signer);

          setCoffeeContract(buyMeACoffee)
        }
        getCoffeContract();
      } catch (error) {
        console.log(error);
      }
    }
  }, [wallet])
  useEffect(() => {
    const onNewCoffee = (from, timestamp, name, message) => {
      console.log("Coffee received: ", from, timestamp, name, message);
      setGetCoffee((prevState) => [
        ...prevState,
        {
          address: from,
          timestamp: new Date(timestamp * 1000),
          message,
          name
        }
      ]);
    };
      if (wallet && coffeeContract) {
        getCoffee()
        coffeeContract.on("NewCoffee", onNewCoffee);    
      } else {
        console.log("provider not initialized yet");
      }
  }, [wallet, coffeeContract])
  const onNameChange = (event) => {
    setName(event.target.value);
  }
  const onMessageChange = (event) => {
    setMessage(event.target.value);
  }
  const buyCoffee = async (e) => {
    e.preventDefault();
    try {
      if (!wallet && !coffeeContract) {
        console.log("provider not initialized yet");
        return;
      }
        console.log("buying coffee..")
        const coffeeTxn = await coffeeContract.buyCoffee(name, message, {value: ethers.parseEther("1.0")});
        const coffeTx =  await coffeeTxn.wait();
        console.log("mined ", coffeTx.hash);
        console.log("coffee sent!");
        // clear target value fields
        e.target.inputName.value = "";
        e.target.inputAmount.value = "";
        // Clear the form fields.
        setName("");
        setMessage("");
        // set all coffees
        await getCoffee();
    } catch (error) {
      console.log(error);
    }
  };

  return (
     <main className='coffeeMain max-w-8xl min-h-[100vh] p-10 bg-black mt-0 shadow-2xl m-auto flex flex-col justify-center items-center bg-[url("https://static.vecteezy.com/system/resources/previews/001/330/185/original/coffee-cup-on-hand-drawn-doodle-background-free-vector.jpg")]'>
        <div className='coffeContent'>
          <div className='compOne flex flex-col justify-center items-center'>
            <h1 className='text-white text-center text-2xl'>Buy me a coffee</h1>
            { wallet ?
            ( <div>
                <form onSubmit={buyCoffee} className="flex flex-col justify-center items-center mt-4">
                  <input type="text" name='inputName' placeholder="Enter your name" className="p-5 rounded-md bg-black text-white border-solid border-2 border-white outline-0" onChange={onNameChange} />
                  <input type="text" name='inputAmount' placeholder="Send your message" className="p-5 rounded-md bg-black text-white border-solid border-2 border-white mt-3 outline-0" onChange={onMessageChange}/>
                  <input type="submit" value="Send Coffee" className="p-3 mt-4 rounded-2xl bg-white text-black cursor-pointer"/>
                </form>
            </div> ) : (    <button className='text-black bg-white p-3 rounded-lg mt-3 cursor-pointer' disabled={connecting} onClick={() => (wallet ? disconnect(wallet) : connect())}>
        {connecting ? 'Connecting' : wallet ? 'Disconnect' : 'Connect'}
      </button>)

            }
          </div>
          <div className="comp2 flex flex-col justify-normal items-center py-3 px-10">
            {wallet && ( 
              <div className="flex mt-5 mb-3">
                  <h1 className="text-white text-2xl">Coffee Transaction</h1>
              </div>
              ) }
              <div className="coffeeTransaction w-[1300px] flex flex-row gap-5 overflow-x-scroll">
              {/* grid gap-4 grid-cols-2 */}
                {wallet && (coffee.map((coff, id) => {
                      return (
                        <div key={id} className=" border-solid border-2 border-white p-5 w-auto rounded-2xl mb-3">
                          <p className=" text-white font-bold">"{coff.message}"</p>
                          <p className=" text-white">From: {coff.name} at {`${new Date(coff.timestamp.toString() * 1000)}`}</p>
                        </div>
                      )
                }))}
              </div>
            </div>
        </div>
    </main>
  )
}

Important notes from the code above

  1. Get your contract ABI: The contract ABI specifies to the frontend code what functions are available to call on the smart contract. To get your contract abi, navigate to your smart-contract folder and copy the text in this file following this path artifacts/contracts/BuyMeACoffee.sol/BuyMeACoffee.json. Next we created a utils folder in the frontend/src folder. Then pasted it in a newly created file named BuyMeACoffee.json file.

  2. Change BMC Contract address to the address of your BMC deployed contract.

Now if the app isn't already running, you can go to the shell and use npm run dev to start a local server to test out your changes. The website should load in a few seconds and UI should look like this:

Connect Wallet Page:

Frontend website to send coffee:

Now let's explore through our website and the code.

You can already see from the above screenshot that when you first visit the dApp, it will ask you to connect a wallet. Next it pops up the list of available wallets initialized in the Web3Onboard instance.

Then you select the wallet of your choice; from the image above, we selected MetaMask. Once you have connected your wallet, you get to see a UI component on the upper right of your website which contains the details of the connected wallet. Also on the page, you will see the coffee transaction form which contains the name and message of the sender, as well as the previous coffee paid into the smart contract by other visitors.

ethers.js
web3.js