本文へスキップ
このページは英語からの機械翻訳を使用しており、誤りや不明瞭な表現が含まれている可能性があります。最も正確な情報については、オリジナルの英語版をご覧ください。頻繁な更新のため、一部のコンテンツはオリジナルの英語になっている可能性があります。Crowdinでの取り組みに参加して、このページの翻訳改善にご協力ください。 (Crowdin translation page, Contributing guide)

書く

スマートコントラクトの状態を更新する必要がある場合、スマートコントラクトと**"トランザクション "**をやり取りすることができる。

web3にkaiaの機能を追加するために、@kaiachain/ethers-extモジュールをインポートしてください。

カイアブロックチェーンとの読み取り専用インタラクションのためのパブリッククライアントを初期化します。

createWalletClientを使用してウォレットクライアントをセットアップし、KairosチェーンHTTPトランスポート、および送信者の秘密鍵**をアカウントに変換して設定します。

solidityコードから生成されたAbiを設定する。

相互作用する契約アドレスを定義する

writeContract`メソッドは、Date.now() (ミリ秒単位の現在のタイムスタンプ)を引数として、コントラクトのsetNumber関数を呼び出すために使用される。 これは、契約のnumber変数を更新するトランザクションを作成し、送信する。

パブリッククライアントを使用して、コントラクトから 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

ページを改善してください。