[CloseSea] 지갑연결 버튼

2022. 12. 28. 11:50·팀프로젝트/close_sea
728x90
반응형

지갑 연결 버튼 컴포넌트

import React from "react";
const ConnectWalletBtn = ({ setAccount }) => {
  const getRequestAccount = async () => {
    const [account] = await window.ethereum.request({
      method: "eth_requestAccounts",
    });
    return account;
  };
  const connectWallet = async () => {
    const account = await getRequestAccount();
    setAccount(account);
    localStorage.setItem("account", account);
    window.ethereum.on("accountsChanged", async () => {
      const account = await getRequestAccount();
      setAccount(account);
      localStorage.setItem("account", account);
    });
  };

  return <div onClick={connectWallet}>지갑 연결</div>;
};

export default ConnectWalletBtn;

window.ethereum은 메타마스크가 있다면 실행할 수 있다.

method에 account를 요청하고 on함수를 통해 account가 바뀌면 감지할수 있도록 설정해놨다.

첫 마운트시 지갑과 네트워크 비교 로직

useEffect(() => {
    if (window.ethereum) {
      const web3 = new Web3(window.ethereum);
      setWeb3(web3);
    }
    (async () => {
      const getAccount = localStorage.getItem("account");
      if (getAccount) {
        const [metaAccount] = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        if (getAccount === metaAccount) {
          setAccount(getAccount);
          window.ethereum.on("accountsChanged", async () => {
            const account = await window.ethereum.request({
              method: "eth_requestAccounts",
            });
            setAccount(account);
            localStorage.setItem("account", account);
          });
          setLoading(true);
          await window.ethereum
            .request({
              jsonrpc: "2.0",
              method: "wallet_switchEthereumChain",
              params: [{ chainId: "0x5" }],
            })
            .catch(() => {
              alert("goerli 네트워크에서만 사용가능");
            });
          setLoading(false);
          window.ethereum.on("chainChanged", async function (networkId) {
            if (networkId !== "0x5") {
              setLoading(true);
              await window.ethereum
                .request({
                  id: 1,
                  jsonrpc: "2.0",
                  method: "wallet_switchEthereumChain",
                  params: [{ chainId: "0x5" }],
                })
                .catch(() => {
                  alert("goerli 네트워크에서만 사용가능");
                });
              setLoading(false);
            }
          });
        }
      }
    })();
  }, []);

account값을 로컬스토리지에 저장해놓고 새로고침시 로컬스토리지에 있는값과 현재 account를 비교했다.

728x90
반응형

'팀프로젝트 > close_sea' 카테고리의 다른 글

[CloseSea] ERC721 tokenURI 연결 이슈  (0) 2022.12.28
[CloseSea] NFT거래 권한 이슈  (0) 2022.12.28
[CloseSea] 스마트 컨트랙트  (1) 2022.12.27
[CloseSea] swap페이지 만들기  (0) 2022.12.27
[CloseSea] eslint, prettier 설정  (0) 2022.12.26
'팀프로젝트/close_sea' 카테고리의 다른 글
  • [CloseSea] ERC721 tokenURI 연결 이슈
  • [CloseSea] NFT거래 권한 이슈
  • [CloseSea] 스마트 컨트랙트
  • [CloseSea] swap페이지 만들기
TeTedo.
TeTedo.
  • TeTedo.
    TeTedo 개발 일기
    TeTedo.
  • 전체
    오늘
    어제
    • 분류 전체보기 (319)
      • 개발 (274)
        • Article (4)
        • 정리 (21)
        • Spring Boot (17)
        • JPA (2)
        • JAVA (6)
        • Database (4)
        • 자료구조 (11)
        • 알고리즘 (32)
        • React (20)
        • Docker (10)
        • node.js (18)
        • Devops (11)
        • Linux (4)
        • TypeScript (3)
        • Go (10)
        • HyperLedger (4)
        • BlockChain (43)
        • html, css, js (48)
        • CS (3)
        • AWS (3)
      • 모아두고 나중에 쓰기 (3)
      • 팀프로젝트 (18)
        • SNS(키보드워리어) (9)
        • close_sea (9)
      • 개인프로젝트 (1)
        • Around Flavor (1)
        • CHAM (13)
        • ethFruitShop (5)
      • 독서 (0)
        • 스프링부트와 AWS로 혼자 구현하는 웹 서비스 (0)
  • 블로그 메뉴

    • 홈
    • 개발일기
    • CS
    • 실습
    • 코딩테스트
    • 웹
    • Go
    • node.js
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    erc20
    node.js
    CSS
    ERC721
    mysql
    node
    하이퍼레저
    블록체인
    nodejs
    html
    go
    명령어
    js
    30일챌린지
    컨테이너
    프로그래머스
    30일 챌린지
    React
    go언어
    도커
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[CloseSea] 지갑연결 버튼
상단으로

티스토리툴바