Hardhat 调用合约方法中参数为结构体struct类型的传参方式

如果一个合约方法中有太多参数,一般超过6个参数时,需要将参数汇总在一个结构体中,若参数都直接写在参数中,使用hardhat中调用时,会报错误“Stack too deep”,其中一个解决方法可以将所有写在一个结构体类型中进行传参,合约如下所示:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "hardhat/console.sol";

struct Param {
    address from;
    address to;
    uint256 amount;
    uint256 p1;
    uint256 p2; 
    uint256 p3;
    uint256 p4;
}

contract MyTestStructParam {

    /*
        @dev 测试参数为结构体对象, 函数体中打印参数值 
        @param _param 一个结构体类型
     */
    function testParam(Param memory _param) public view {        
        console.log("from:", _param.from);
        console.log("to:", _param.to);
        console.log("amount:", _param.amount);
        console.log("p1:", _param.p1);
        console.log("p2:", _param.p2);
        console.log("p3:", _param.p3);
        console.log("p4:", _param.p4);
    }   
}

Hardhat中测试代码:

//导入 Hardhat 管理器和 Chai 断言库
const { ethers } = require('hardhat');
const { defaultAbiCoder } = require("ethers").utils;

describe("测试hard调用合约方法含结构体参数的传参方式", function () {

    it("测试结果", async function () { 
        //获取钱包对象     
        const [owner, to] = await ethers.getSigners();   
        //部署合约
        const ContractFactory = await ethers.getContractFactory("MyTestStructParam");
        const myContract = await ContractFactory.deploy();

        // 参数
        const paramInfo = {
            from: owner.address,
            to: to.address,
            amount: 888,
            p1: 1,
            p2: 1000,
            p3: 500,
            p4: 26
        };
    
        // 调用合约方法
        await myContract.testParam(paramInfo);     
    });
});

Hardhat使用可参见:Hardhat创建、编译、测试智能合约_瘦身小蚂蚁的博客-CSDN博客

Supongo que te gusta

Origin blog.csdn.net/ling1998/article/details/129540819
Recomendado
Clasificación