这里介绍一下基本的函数语法
我写一个示例
Function.sol
contract FunctionIntro {
function add(uint x, uint y) public pure returns (uint) { return x + y; }
function sub(uint x, uint y) public pure returns (uint) { return x - y; }
}
这里是一个简单的函数,包含输入,returns
我写一个脚本调用它试一试会运行出什么样的结果
function.js
const hre = require("hardhat");
async function main() {
const FunctionIntro = await hre.ethers.getContractFactory("FunctionIntro");
const f = await FunctionIntro.deploy();
await f.waitForDeployment();
console.log("add(5,3) =", (await f.add(5, 3)).toString());
console.log("sub(5,3) =", (await f.sub(5, 3)).toString());
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
然后运行
add(5,3) = 8
sub(5,3) = 2
调用方法就是 await 合约.add(5, 3),因为 add/sub 都是 pure 函数,直接返回结果。
一个坑提醒:uint 不能是负数,所以 sub(3, 5) 会报错(revert)。要支持负数得用 int 类型。
