블록체인
메타마스크를 통한 이더리움 지갑연결 truffle이용한 배포및 테스트 그리고 빌드 web3라이브러리
Counter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract Counter{
uint256 private value;
// function setValue(uint256 _value) public {
// value = _value;
// }
function increment() public {
value +=1;
}
function decrement() public {
value -=1;
}
function getValue() public view returns(uint256) {
return value;
}
}
truffle init, sol 작성후 truffle compile truffle migrate.
migrations
// 빌드폴더안에 컴파일된 Counter.json 을가져온다.
const Counter = artifacts.require("Counter");
// 배포관련된 객체가 들어온다
module.exports = (deployer) => {
// deployer.deploy 메서드로
// 가져온 json 파일 내용으로 배포를 진행
deployer.deploy(Counter);
};
build는 json 파일로 생성된다. src abi 폴더에 들어간다.
ganche-cli 로 가상 이더환경테스트
npx ganache-cli
private key, public key 생성
react로 ui 구현
import { useEffect, useState } from "react";
import useWeb3 from "./hooks/web3.hook";
import abi from "./abi/Counter.json";
const App = () => {
const { user, web3 } = useWeb3();
const [count, setCount] = useState("0");
const [countContract, setCountCountract] = useState(null);
useEffect(() => {
if (web3 !== null) {
if (countContract === null) {
// web3.eth.Contract : 네트워크에 배포되어있는 컨트랙트를 조회하고 인스턴스로 생성해둔다
// 메소드를 통해서 네트워크에 상호작용 할수있다.
// web3.eth.Contract = (abi, CA, option)
// {data : ""} 빈값으로 일단 디폴트 옵션 추가
const Counter = new web3.eth.Contract(
abi,
"0x5bDAe9FC399EE345B3a1B5Fb63F05fcE1b56e02A",
{ data: "", from: "" }
);
// 이후에 디폴트 옵션을 추가하고싶다 하면
// 객체의 키값에 직접 추가해도 된다.
Counter.options.from = "0x000";
setCountCountract(Counter);
}
}
}, [web3]);
const getValue = async () => {
if (countContract === null) return;
const result = web3.utils
.toBigInt(await countContract.methods.getValue().call())
.toString(10);
setCount(result);
};
const increment = async () => {
await countContract.methods.increment().send({
from: user.account,
data: countContract.methods.increment().encodeABI(),
});
getValue();
};
const decrement = async () => {
await countContract.methods.decrement().send({
from: user.account,
data: countContract.methods.decrement().encodeABI(),
});
getValue();
};
useEffect(() => {
if (countContract !== null) getValue();
}, [countContract]);
if (user.account === null) return "연결된 지갑 주소가 없음";
return (
<>
<div>{user.account}</div>
<div>카운터 : {count}</div>
<button onClick={increment}>증가</button>
<button onClick={decrement}>감소</button>
</>
);
};
export default App;
메타마스크와 ganche 환경연결을 위한 web3 커스텀 훅
import { useState, useEffect } from "react";
import Web3 from "web3";
const useWeb3 = () => {
const [user, setUser] = useState({
account: "",
balance: "",
});
const [web3, setWeb3] = useState(null);
useEffect(() => {
if (window.ethereum) {
window.ethereum
.request({
method: "eth_requestAccounts",
})
.then(async ([data]) => {
const web3Provider = new Web3(window.ethereum);
setUser({
account: data,
balance: web3Provider.utils.toWei(
await web3Provider.eth.getBalance(data),
"ether"
),
});
setWeb3(web3Provider);
});
} else {
alert("메타마스크 설치하세요");
}
}, []);
return {
user,
web3,
};
};
export default useWeb3;
문제점 setWeb3 위치
불편한점
sol 파일에 변경사항이 있을때마다 truffle compile, truffle migrate 를 반복해서 사용해줘야하며
useEffect(() => {
if (web3 !== null) {
if (BaseballContract === null) {
const Baseball = new web3.eth.Contract(
abi,
"0x94832d64A02A7C3d0D3b0F8d574c1274df6d6b22",
{ data: "" }
);
SetBaseballContract(Baseball);
}
}
}, [web3]);
new web.eth.Contract 생성시 들어가는 매개변수들 abi, 두번쨰 매개변수값 CA 값을 해당하는 address 에맞게 계속 바꿔주어야한다.
아직 의문인점:
call하고 send 의 차이점 send call 이면 from혹은 value를 안쓰는줄았는데 그것도아님
'backend > blockchain' 카테고리의 다른 글
| 20231005 블록체인 baseball (1) | 2023.10.05 |
|---|---|
| 20230912 블록 체인 지갑 (0) | 2023.09.12 |
| 블록체인 (0) | 2023.09.05 |
| 블록체인 블록생성, 검증,테스트 ts (0) | 2023.09.04 |