跳至主要内容
本页面使用机器翻译自英语,可能包含错误或不清楚的语言。如需最准确的信息,请参阅英文原文。由于更新频繁,部分内容可能与英文原文有出入。请加入我们在 Crowdin 上的努力,帮助我们改进本页面的翻译。 (Crowdin translation page, Contributing guide)

当您需要更新智能合约中的某些状态时,您可以与智能合约进行**"事务 "**交互。

导入 @kaiachain/ethers-ext 模块,在 web3 上添加 kaia 功能。

初始化公共客户端,用于与 Kaia 区块链进行只读交互。

使用createWalletClient建立钱包客户端,配置Kairos链HTTP传输和转换为账户的发送者私钥

设置从 solidity 代码生成的 Abi

定义与之交互的**合同地址

写合约 "方法用于调用合约上的 setNumber 函数,参数为 Date.now()(当前时间戳,以毫秒为单位)。 这将创建并发送一个事务来更新合同的 number 变量。

使用公共客户端从合约中查询 number 函数(一个不修改状态的视图函数)。 这将检索数字变量的当前值,该值应反映上一个事务(如果成功)所设置的时间戳。

smartContractWrite.js

import {
createPublicClient,
http,
kairos,
privateKeyToAccount,
createWalletClient
} from "@kaiachain/viem-ext";
const publicClient = createPublicClient({
chain: kairos,
transport: http(),
});
const walletClient = createWalletClient({
chain: kairos,
transport: http(),
account: privateKeyToAccount(
// using legacy account only for this example
"0x71c5a2d04d744d76492640fb3e5cf2650efae106655f27baffc482c53f57dca2"
),
});
// 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 txHash = await walletClient.writeContract({
address,
abi,
functionName: 'setNumber',
args: [Date.now()]
})
console.log('tx hash', txHash);
const result = await publicClient.readContract({
address,
abi,
functionName: 'number'
})
console.log('Current contract value', result);
})();

output

❯ node smartContractWrite.js
tx hash 0xf890d27d3cb4670755391257477c4f942ecb3fd0974e1863c2cd0bc72bfae0d4
Current contract value 123n

让这个页面变得更好