Solidity
如何使用打字稿中的自定義結構呼叫外部合約函式
我有這個基本的契約:
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "hardhat/console.sol"; contract Greeter { struct Greeting { uint8 id; string text; } Greeting[] public greetings; string private greeting; constructor(string memory _greeting) { greeting = _greeting; } function greet() public view returns (string memory) { return greeting; } function setGreeting(string memory _greeting) public { greeting = _greeting; } function setGreetings(Greeting[] calldata _greetings) external { for (uint16 i = 0; i < _greetings.length; i++) { greetings.push(_greetings[i]); } } }
我嘗試
setGreetings
從以下位置撥打電話ethers.js
:const Greeter = await ethers.getContract("Greeter") await Greeter.setGreetings([[0, "Hello, Hardhat!"]]);
但我收到:
Error: missing argument: passed to contract (count=0, expectedCount=1, code=MISSING_ARGUMENT, version=contracts/5.5.0)
雖然我確實設法
setGreeting
用字元串輸入呼叫:await Greeter.setGreeting("Hello, Hardhat!"); expect(await Greeter.greet()).to.equal("Hello, Hardhat!");
您可以使用以下程式碼作為 setGreetings 的測試:
import { BigNumber } from "ethers"; import { ethers } from "hardhat"; describe("Greeter", function () { it("Should set greetings", async function () { const Greeter = await ethers.getContractFactory("Greeter"); const greeter = await Greeter.deploy("Hello, world!"); await greeter.deployed(); const greetings = { id: BigNumber.from(0), text: "Hello, Hardhat!", } const setGreetingsTx = await greeter.setGreetings([greetings]); // wait until the transaction is mined await setGreetingsTx.wait(); }); });