跳至主要內容
本頁面使用機器翻譯自英語,可能包含錯誤或不清楚的語言。如需最準確的信息,請參閱英文原文。由於更新頻繁,部分內容可能與英文原文有出入。請加入我們在 Crowdin 上的努力,幫助我們改進本頁面的翻譯。 (Crowdin translation page, Contributing guide)

撰寫

當您需要更新契約中的某些狀態時,您可以進行**「交易」**與智慧契約互動。

匯入 @kaiachain/ethers-ext 模組,在 web3 上加入 kaia 功能。

初始化用於與 Kaia 區塊鏈進行唯讀互動的公共用戶端。

使用 createWalletClient 設定一個錢包用戶端,並配置 Kairos 鏈HTTP 傳輸,以及轉換為帳戶的寄件者私密金鑰

設定由 solidity 代碼產生的 Abi

定義合約位址進行互動

writeContract 方法用來呼叫合約上的 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

讓這個頁面變得更好