跳至主要內容
本頁面使用機器翻譯自英語,可能包含錯誤或不清楚的語言。如需最準確的信息,請參閱英文原文。由於更新頻繁,部分內容可能與英文原文有出入。請加入我們在 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 @kaiachain/ethers-ext modules to add kaia features on web3.

Initializes a public client for read-only interactions with the Kaia blockchain.

Set the Abi generated from solidity code

Define contract address to interact with

The readContract method is called on the public client to query the number function (a view function that doesn’t modify state) from the contract at the specified address.

SmartContractView.js

import { http, createPublicClient, kairos } from "@kaiachain/viem-ext";
const publicClient = createPublicClient({
chain: kairos,
transport: http(),
});
// Example usage
(async () => {
const abi = [{ "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 address = "0x95Be48607498109030592C08aDC9577c7C2dD505";
const result = await publicClient.readContract({
address,
abi,
functionName: 'number'
})
console.log('Current contract value', result);
})();

output

❯ js SmartContractView.js
Current contract value 123n

讓這個頁面變得更好