在Remix中运行合约JS脚本

Remix 接受 async/await 脚本来运行 web3.js 或 ethers.js 命令。脚本需要包装在一个自执行函数中。如下:

// Right click on the script name and hit "Run" to execute
(async () => {
    try {
        console.log('Running deployWithWeb3 script...')
        
        const contractName = 'Storage' // Change this for other contract
        const constructorArgs = []    // Put constructor args (if any) here for your contract
    
        // Note that the script needs the ABI which is generated from the compilation artifact.
        // Make sure contract is compiled and artifacts are generated
        const artifactsPath = `browser/contracts/artifacts/${contractName}.json` // Change this for different path

        const metadata = JSON.parse(await remix.call('fileManager', 'getFile', artifactsPath))
        const accounts = await web3.eth.getAccounts()
    
        let contract = new web3.eth.Contract(metadata.abi)
    
        contract = contract.deploy({
            data: metadata.data.bytecode.object,
            arguments: constructorArgs
        })
    
        const newContractInstance = await contract.send({
            from: accounts[0],
            gas: 1500000,
            gasPrice: '30000000000'
        })
        console.log('Contract deployed at address: ', newContractInstance.options.address)
    } catch (e) {
        console.log(e.message)
    }
  })()

为什么在 Remix 中运行 JavaScript 脚本?

  • 使用 web3.js 或 ethers.js库,来整合dapp应用的前端。
  • 在不通过 Remix GUI 的情况下快速部署并与一堆合约实例交互。
  • 在之前部署的合约上运行一些测试以进行安全检查。
  • 对更新后的dapp代码进行测试。

Set up

1、这些脚本需要访问合约的 ABI。ABI 位于合约的元数据文件(metadata)中,通过Settings模块并检查Generate contract metadata选项是否确实已选中,确保将创建此元数据文件。

 

2、编译solidity文件,会在工作空间contracts目录中创建artifacts文件夹,里面包含JSON文件的合约元数据。

注意:编译时,不要担心使用与 Async/await 脚本相关的 Solidity 版本——它们适用于所有 Solidity 版本

 3、进入Deploy & Run 模块设置环境,Async/await 脚本适用于所有环境:JavascriptVM、Injected Web3 (metamask) 和 Web3 Provider。

 4、编写脚本。(参考官方相关示例

 5、执行脚本。这里提供了两种方式:

 (1). 使脚本成为编辑器中的活动文件并在控制台中运行remix.exeCurrent()

 (2). 右键单击文件资源管理器中的脚本以获取弹出菜单(参见下图)并选择run选项。

 默认在工作空间的scripts文件夹中,有 2 个示例文件:一个使用web3.js,另一个使用ethers.js

 但是,控制台执行remix.exeCurrent()后,显示 scriptRunner plugin is already rendered,这渲染到哪儿了呀??打开浏览器控制台得到的result是个undefined又是什么鬼?这部分还没搞明白,希望有了解的伙伴能提供帮助~,,,

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值