web3를 이용해 nodeJS환경에서 컨트랙트를 호출할 수 있다.
const ContractABI = require('./abi/Contract.json')
const Web3 = require('web3');
const ContractAddr = "컨트랙트 주소";
let web3 = new Web3('http://127.0.0.1:7545');
var myContract = new web3.eth.Contract(ContractABI, ContractAddr);
//functionName은 컨트랙트에서 호출할 함수 이름을 작성해준다.
async function Test(parameter){
const result = await myContract.methods.functionName(parameter).call();
return result;
}
조건없는 query함수 같은 경우는 위와 같이 call()
을 사용해 호출할 수 있지만
특정 주소에서만 호출할 수 있는 함수는 call()
대신 send({from:'address'})
를 사용하여 호출주소를 설정해줘야 한다.
async function Test(parameter, fromAddr){
const result = await myContract.methods.functionName(parameter)
.send({from: fromAddr});
return result;
}
아래 코드로 새로운 계정을 생성하고 해당 계정의 퍼블릭키와 프라이빗키를 불러올 수 있다.
const newAccount = await web3.eth.accounts.create();
const address = newAccount.address;
const privateKey = newAccount.privateKey
'TXRejectedError: sender account not recognized' 에러 해결하기
이렇게 생성한 계정은 send({from:'addrss'})
로는 함수를 호출할 수 없다. 가나슈에 프라이빗키가 등록되어 있지 않기 때문에 address, 즉 퍼블릭키만으로는 권한을 증명할 수 없기 때문이다.
그렇기 때문에 트랜잭션을 생성하고 프라이빗키로 사인을 한 후 트랜잭션을 전송해야한다.
const Tx = require('ethereumjs-tx').Transaction
const ContractAddr = "컨트랙트 주소";
async function Test (parameter, fromAddr, fromPrivateKey){
const privateKeyBuffer = Buffer.from(fromPrivateKey, 'hex')
nonce = await web3.eth.getTransactionCount(fromAddr)
const tx = {
nonce : nonce,
from: fromAddr,
to: ContractAddr, // smart contract address
gas: "0x218520", //원하는 gas limit 설정
value: "0x0", //지불할 값 설정
//data에 호출할 함수와 파라미터를 넣어주고 ABI를 불러온다.
data: myContract.methods.functionName(parameter).encodeABI()
};
var _tx = new Tx(tx);
_tx.sign(privateKey1Buffer);
var serializedTx = _tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
}
위와 같은 형식의 코드를 작성하면 네트워크에 등록되지 않은 계정을 주체로하는 트랜잭션을 전송할 수 있다.