Skip to content

3 Web3 컨트랙트 연동

MoSangIl edited this page Sep 8, 2021 · 5 revisions

web3 설치 및 적용 방법 (프로젝트에 적용 되어 있음)

web3 설치

npm install web3

package.json 파일 dependencies에 web3 설치 확인

"dependencies": {
"web3": "^1.5.2"
},

index.html 파일 부분에 <script>부분 추가

<head>
<script src="node_modules/web3/dist/web3.min.js"></script>
</head>

배포한 contract 불러오기

frontend 폴더 안에 contracts 파일 생성

경로주의! (frontend 프로젝트 폴더 안)

C:\Users\admin\gitFolder\frontend> mkdir contracts

배포가 완료된 Demo.json 파일 가져오기

  1. chainserver/build/contracts 안에 있는 Demo.json 파일 복사
  2. frontend/contracts 에 붙여넣기

test.js 파일 주소 수정

function getContractWithFetch() {
  fetch("./contracts/Demo.json")
    .then((response) => response.json())
    .then((data) => {
      // change to contract address (Demo)
      const address = "0x9b0C0f91f9148D2bCd60075b146551900f00f423"; // Demo contract address
      const ABI = data.abi;
      contracts.Demo = new web3.eth.Contract(ABI, address);
      console.log(contracts.Demo);
    });
}
const address = "0x3eA2073DE1aaAA3A03D189eC5114F15e5f555021";

"0x3eA2073DE1aaAA3A03D189eC5114F15e5f555021" 부분 자신이 배포한 Demo contract 주소로 변경

contract method 호출

컨트랙트 testing 함수 코드

function testing() public returns (string memory) {
    return "hello world";
  }

testing 함수 호출하기

function onCallMethodBtn(event) {
  event.preventDefault();
  contracts.Demo.methods
    .testing()
    .call()
    .then((data) => {
      alert(`Succed! call the contracts methods! => ${data}`);
    });
}

Test

  1. localhost:9000 (프로젝트 실행 후)
npm run dev
  1. '컨트랙트 함수 테스트' 버튼 클릭
  2. Success 알람 확인.