[TIL] Part2 - DAY58 Solidity - 이론 TEST2, react+web3, react+ethers

박동우·2023년 6월 15일

블록체인 스쿨 3기

목록 보기
54/72

[TIL] 2023-06-15 DAY58


Solidity

GIT 주소 : https://github.com/dowoo303/SOLIDITY


오늘 배운것들

  1. 이론 TEST2
  2. react와 web3 연결해보기
  3. react와 ethers 연결해보기

각종 팁

  1. subscription.on은 상대적으로 느리다.(완전 실시간은 아님)

회고




💻 Solidity 코딩

📕 이더리움 이론

기본적으로 이더리움에서 거래라는 의미는 상태를 변화시켜주는 것이다.
블록은 상태를 변화시켜주는 거래들을 모아놓은 일련의 거래이다.



✅ web3와 react 연결

블록넘버가 바뀔 때마다 업데이트 되도록 react와 web3연결해서 만들어보기
잔고랑 지갑주소도 react+web3로 화면에 나타내보기

- web3
npm init
npm install web3

node
var {Web3} = require('web3')
var web3 = new Web3('ws infura키')
var subscription = await web3.eth.subscribe('newHeads');
subscription.on('data', async blockHead=>{console.log("newBlockHeader:",blockHead)})	// 블록 생성될때마다 가져옴

- 리액트

create-react-app 0615
npm run start

🟥 코드

import React from "react";
import { useEffect, useState } from "react";
import Web3 from "web3";
import { ethers } from "ethers";

// ethers
function App() {
  const [account, setAccount] = useState();
  const [balance, setBalance] = useState();

  const connect = async () => {
    // 내가 보는 화면에서 메타마스크가 있으면 바로 실행
    if (window.ethereum) {
      try {
        const res = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        setAccount(res[0]);

        const _balance = await window.ethereum.request({
          method: "eth_getBalance",
          params: [res[0].toString(), "latest"],
        });
        setBalance(Number(_balance));
      } catch (err) {
        console.error(err);
      }
    } else {
      console.log("install metamask");
    }
  };

  connect();

  return (
    <div>
      <h3>current wallet address : {account}</h3>
      <h3>current balance : {balance}</h3>
    </div>
  );
}

/* web3
function App() {
  const [blockNumber, setblockNumber] = useState();
  const [balance, setBalance] = useState();

  const web3 = new Web3(
    "wss://goerli.infura.io/ws/v3/c9272c6607724aa08e2432def393cb43"
  );

  const privateKey =
    "0xe30d7cfa303f3f5f018409c094ac5363287dcd233ad4b27d5c4d8efa641b0615";
  const account = web3.eth.accounts.privateKeyToAccount(privateKey).address;

  useEffect(() => {
    async function getBlock() {
      const blockNumber = await web3.eth.getBlockNumber();
      setblockNumber(Number(blockNumber));
    }
    getBlock();

    async function subscribeBlock() {
      const subscription = await web3.eth.subscribe("newHeads");
      subscription.on("data", async (blockhead) => {
        console.log("Hash of New Block : ", blockhead.number);
        setblockNumber(Number(blockhead.number));
      });
    }
    subscribeBlock();

    async function getBalance() {
      var balance = await web3.eth.getBalance(account);
      setBalance(Number(balance)); // 형변환
    }
    getBalance();
  });

  return (
    <div>
      <li>current block number is : {blockNumber}</li>
      <li>current Wallet : {account}</li>
      <li>current balance : {balance / 1000000000000000000} eth</li>
    </div>
  );
}
*/

export default App;


profile
HELLO!

0개의 댓글