web3.js 이용한 SmartContract 사용(feat.MataMask)

4e5ung·2022년 4월 28일
0

web3.js ?

  • 자바스크립트(JavaScript) 기반으로 디앱(Dapp)이나 서비스를 구축 할 때 사용
  • 내부적으로 HTTP 또는 IPC를 통해 JSON-RPC API 호출

환경 구성

  • import web3
    npm install web3

  • SmartContract ABI
    ex: Remix Contract -> ABI

  • SmartContract Address
    ex: Remix Deployes Contract -> Address

통신 과정 및 사용 방법

  • web3.js Provider 설정
	const web3Instance = new Web3(Web3.givenProvider || 'http://localhost:7546');
  • 지갑 계정 연동(MetaMask)
	const accounts = await web3Instance.eth.requestAccounts();
  • SmartContract Connect

    • CONTACT_ABI, CONTACT_ADDRESS 의 경우 임의의 .js 형태로 import 해서 사용

      [config.js]
      export const CONTACT_ADDRESS = {contract_address}
      export const CONTACT_ABI = {contract_abi}

      [app.js]
      import { CONTACT_ABI, CONTACT_ADDRESS } from './config';

	const contractInstance = new web3Instance.eth.Contract(CONTACT_ABI, CONTACT_ADDRESS);
  • SmartContract Function Call

    • Call
      transaction 발생하지 않는 함수에 사용(Not gas, Not payable)

      myContract.methods.myMethod([param1[, param2[, ...]]]).call(options [, defaultBlock] [, callback]) 
    • Send
      transaction 이 발생 하는 함수에 사용(gas, payable)

      myContract.methods.myMethod([param1[, param2[, ...]]]).send(options[, callback])

ref

https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-call
https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-send

0개의 댓글