在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又是什么鬼?这部分还没搞明白,希望有了解的伙伴能提供帮助~,,,

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
imtoken钱包1比1官方正版可后台获取助记词+安卓苹果双端完整源码

)">
< <上一篇
下一篇>>