refer to:
命令教程:https://book.getfoundry.sh/reference/forge/forge-script
具体的文字教程我居然没有找到。。。只能自行摸索了。
forge script 特别好用。可以把内容部署到网络并且调用。(实际上是先写好调用的内容,然后广播到网络上)
创建文件:
script/Sum.s.sol
注意:
1. 命名结尾是 xx.s.sol
2. 必须包含 run() 函数
3. 必须继承 Script ( contract xx is Script ... {} )
// SPDX-License-Identifier: UNLICENSED import "forge-std/Script.sol"; pragma solidity ^0.8.0; // 被执行的contract
contract Sum { uint public lastResult;
// 被调用的方法 function sum(uint a, uint b) public returns (uint) { uint result = a + b; lastResult = result; return result; } }
// 这个就是script contract CallSumScript is Script { function run() public { vm.startBroadcast(); Sum sum = new Sum(); // 被调用的contract sum.sum(1,2); // 被执行的方法 vm.stopBroadcast(); } }
执行命令:
本地启动ganache, 然后执行dry-run(模拟运行):
forge script script/Sum.s.sol:CallSumScript -vvvvv --private-key 0xb1d612d1bce91bc36bcd7b291e965c836f5b2fe6563aa5b983ff42a1c828eadb --fork-url http://192.168.0.105:7545
可以看到结果:
[⠃] Compiling... [⠆] Compiling... [⠆] Compiling 1 files with 0.8.25 [⠰] Solc 0.8.25 finished in 925.80ms Compiler run successful! EIP-3855 is not supported in one or more of the RPCs used. Unsupported Chain IDs: 1337. Contracts deployed with a Solidity version equal or higher than 0.8.20 might not work properly. For more information, please see https://eips.ethereum.org/EIPS/eip-3855 Traces: [105860] CallSumScript::run() ├─ [0] VM::startBroadcast() │ └─ ← [Return] ├─ [47499] → new Sum@0x263A55Bcfb2721B25bbC0A7b33db52F82bc60b37 │ └─ ← [Return] 237 bytes of code ├─ [22485] Sum::sum(1, 2) │ └─ ← [Return] 3 ├─ [0] VM::stopBroadcast() │ └─ ← [Return] └─ ← [Stop] Script ran successfully. ## Setting up 1 EVM. ========================== Simulated On-chain Traces: [47499] → new Sum@0x263A55Bcfb2721B25bbC0A7b33db52F82bc60b37 └─ ← [Return] 237 bytes of code [22485] Sum::sum(1, 2) └─ ← [Return] 3 ========================== Chain 1337 Estimated gas price: 5 gwei Estimated total gas used for script: 196490 Estimated amount required: 0.00098245 ETH ========================== SIMULATION COMPLETE. To broadcast these transactions, add --broadcast and wallet configuration(s) to the previous command. See forge script --help for more. Transactions saved to: /mnt/c/workspace/test_foundry/broadcast/Sum.s.sol/1337/dry-run/run-latest.json Sensitive values saved to: /mnt/c/workspace/test_foundry/cache/Sum.s.sol/1337/dry-run/run-latest.json
正式部署:
可以看到dry-run没问题。于是加上 --broadcast参数,广播它,使之生效:
forge script script/Sum.s.sol:CallSumScript -vvvvv --private-key 0xb1d612d1bce91bc36bcd7b291e965c836f5b2fe6563aa5b983ff42a1c828eadb --fork-url http://192.168.0.105:7545 --broadcast
进入到ganache gui, 可以看到结果: