You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Foundry脚本中通过加密密钥库账户设置msg.sender

Foundry部署脚本切换账户的解决方案

核心结论:无需修改现有脚本(推荐方式)

你当前的脚本代码不需要任何改动,只要在CLI执行时带上--account myDeployer参数,vm.startBroadcast()会自动加载~/.foundry/keystores/myDeployer密钥库对应的账户作为签名者,此时msg.sender就是该密钥库关联的地址。

运行脚本时会弹出密码输入提示,输入该密钥库的加密密码即可正常执行广播操作。

手动指定账户的代码实现(灵活场景)

如果需要在脚本中主动切换账户,有两种常用方式:

方式1:通过环境变量传入私钥(适合测试环境)

在脚本中读取环境变量中的私钥,传入vm.startBroadcast():

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.21;

import {Script, console2} from "forge-std/Script.sol";

contract CheckKeyExample is Script {
    function run() public {
        // 从环境变量读取私钥
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        // 传入私钥启动广播
        vm.startBroadcast(deployerPrivateKey);
        
        console2.log(msg.sender); // 此时msg.sender是私钥对应的地址
        address payable geteth = payable(address(this));
        geteth.transfer(1);
        
        vm.stopBroadcast();
    }
}

运行时设置环境变量:

PRIVATE_KEY=你的私钥 forge script script/CheckKey.s.sol:CheckKey --broadcast

方式2:直接加载密钥库文件

在脚本中指定密钥库路径,读取密码后加载账户:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.21;

import {Script, console2} from "forge-std/Script.sol";

contract CheckKeyExample is Script {
    function run() public {
        // 指定密钥库路径
        string memory keystorePath = "~/.foundry/keystores/myDeployer";
        // 读取密码输入
        string memory password = vm.readPassword("输入密钥库密码:");
        // 加载密钥库获取私钥
        uint256 deployerPrivateKey = vm.loadWallet(keystorePath, password);
        
        vm.startBroadcast(deployerPrivateKey);
        console2.log(msg.sender); // 对应myDeployer的地址
        address payable geteth = payable(address(this));
        geteth.transfer(1);
        vm.stopBroadcast();
    }
}

运行时无需--account参数,直接执行:

forge script script/CheckKey.s.sol:CheckKey --broadcast

内容的提问来源于stack exchange,提问作者Max S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:25:13