본문으로 건너뛰기
이 페이지는 영어로 된 기계 번역을 사용하므로 오류나 불명확한 언어가 포함될 수 있습니다. 가장 정확한 정보는 영어 원문을 참조하시기 바랍니다. 잦은 업데이트로 인해 일부 콘텐츠는 원래 영어로 되어 있을 수 있습니다. Crowdin에서 이 페이지의 번역을 개선하는 데 동참하여 도움을 주세요. (Crowdin translation page, Contributing guide)

Read

You can call functions in Smart Contract via "Call" RPC API. What you can call here is limited to view functions that is not changing any states in the Contract.

Import the web3 and @kaiachain/web3js-ext packages to add kaia features on web3

Set up the provider with the specified kairos testnet URL. A provider in web3js is a read-only abstraction to access the blockchain data.

Also, you can change the provider URL from kairos to quicknode

Define contract Abi and addreess, you can get it from compiled solidity code

Create a contract instance using Web3.eth.Contract with defined contractAbi and address. You can read and write the contract through this instance

Call function number of created contract and print the result

smartContractRead.js

const { Web3 } = require("@kaiachain/web3js-ext");
const provider = new Web3.providers.HttpProvider("https://public-en-kairos.node.kaia.io");
const web3 = new Web3(provider);
/* compiled in remix.ethereum.org (compiler: 0.8.18, optimizer: false)
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
contract Counter {
uint256 public number;
event SetNumber(uint256 number);
constructor(uint256 initNumber) {
number = initNumber;
}
function setNumber(uint256 newNumber) public {
number = newNumber;
emit SetNumber(number);
}
function increment() public {
number++;
emit SetNumber(number);
}
}
*/
const contractAbi = JSON.parse('[{"inputs":[{"internalType":"uint256","name":"initNumber","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"number","type":"uint256"}],"name":"SetNumber","type":"event"},{"inputs":[],"name":"increment","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"number","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"newNumber","type":"uint256"}],"name":"setNumber","outputs":[],"stateMutability":"nonpayable","type":"function"}]');
const contractAddr = "0x95Be48607498109030592C08aDC9577c7C2dD505";
async function main() {
const contract = new web3.eth.Contract(contractAbi, contractAddr);
const number = await contract.methods.number().call();
console.log("number", number.toString());
}
main();

output

❯ node smartContractRead.js
number 294

페이지를 개선해 주세요