Web3.js 스마트 컨트랙트 실행하기

반영환·2023년 5월 31일
0

BlockChainDev

목록 보기
4/11
post-thumbnail

Web3.js 스마트 컨트랙트 실행하기

Depreciated

해당 내용은 컨셉은 일치하나 함수는 실행되지 않습니다.

스마트 컨트랙트 컴파일

solc : solidity를 JSON형태로 컴파일 해주는 모듈

solc로 컴파일된 JSON파일을 abi와 bytecode로 나누어서 저장해야 한다.

스마트 컨트랙트 Deploy

  1. web3.eth.Contract 를 통해 객체를 생성

  2. Deploy는 위에서 컴파일한 bytecode와 스마트컨트랙트를 실행할 account를 작성. 이 값을 ABI값으로 변경

  1. getTransactionCount 함수를 사용하여 Nonce값을 구하고, Object의 data에는 ABI값이 저장된 deploy로 할당.(단, abi로 변환한 값을 hex값 형식으로 변환해야 함. 때문에 ‘0x’를 앞에다가 붙여주자) 이 Object를 web3.eth.sendSignedTransaction 함수를 통해서 트랜잭션을 이더리움블록체인에 실행시키면 된다.

  2. 이상없이 contract가 생성되면 결과값으로 contractAddress가 나오는데 함수를 call할 때 이 contractAddress가 꼭 필요하다.

스마트 컨트랙트 실행

컨트랙트 실행할 때 객체를 생성 시, contractAddress 값을 넣어서 객체를 생성
중요한 것은 앞서 스마트컨트랙트를 실행시킨 Transaction Hash값을 알고 있어야 한다.
Transaction Hash를 관리할 방법을 고민해보자.

var express = require('express');
var app = express();
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws'));
var Tx = require('ethereumjs-tx');

const send_account    = "0x82Ff486364ebDbEe1b34b7538ceD72448d9b38cb";
const receive_account = "0xf2a58d3F268642f7f5416F4248f4Fb2623a5D929";
const privateKey = Buffer.from('privateKey', 'hex');


var solc = require('solc'); //contract Compile
var fs = require('fs'); //file 시스템

app.get('/smartcontract', function(req,res){
  //File Read
  var source = fs.readFileSync("./contracts/HelloWorld.sol", "utf8");

  console.log('transaction...compiling contract .....');
  let compiledContract = solc.compile(source);
  console.log('done!!' + compiledContract);

  var bytecode = '';
  var abi = '';
  for (let contractName in compiledContract.contracts) {
     // code and ABI that are needed by web3
     abi = JSON.parse(compiledContract.contracts[contractName].interface);
     bytecode = compiledContract.contracts[contractName].bytecode; //컨트랙트 생성시 바이트코드로 등록
     // contjson파일을 저장
  }
  console.log(abi);

  const MyContract = new web3.eth.Contract(abi);

  let deploy = MyContract.deploy({
                 data: bytecode,
                 from: send_account}).encodeABI();
  //deploy
  web3.eth.getTransactionCount(send_account, (err, txCount) => {

  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    gasLimit: web3.utils.toHex(1000000), // Raise the gas limit to a much higher amount
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
    data : '0x' + deploy
  };

  const tx = new Tx(txObject);
  tx.sign(privateKey);

  const serializedTx = tx.serialize();
  const raw = '0x' + serializedTx.toString('hex');

  web3.eth.sendSignedTransaction(raw)
     .once('transactionHash', (hash) => {
       console.info('transactionHash', 'https://ropsten.etherscan.io/tx/' + hash);
     })
     .once('receipt', (receipt) => {
       console.info('receipt', receipt);
    }).on('error', console.error);
  });

});

//app을 listen
app.listen(4000, function(){
  console.log('Connected BlockChain, 4000 port!');
});

출처

이더리움 블록체인_Web3.js 스마트컨트랙트 실행하기

profile
최고의 오늘을 꿈꾸는 개발자

0개의 댓글

관련 채용 정보