运行脚本

JavaScript(JS)是一种轻量级、解释型或即时编译的编程语言,具有一等函数。

Remix IDE 支持执行 JS 脚本。

编写并运行脚本

创建一个扩展名为.js的文件,并编写逻辑代码。一旦准备就绪,有两种方法来运行此脚本:

  1. 在编辑器中将脚本设置为选中文件,并在 Remix 终端运行 remix.exeCurrent()

  2. Files Explorers插件中,右键单击脚本名称,然后点击Run选项。在编辑器中显示脚本时,快捷键为Ctrl+Shift+S

这里是一个示例脚本:

function test() {
  var num=12;
  if(num<10)
    console.log(num + " is less than 10");
  else
    console.log(num + " is not less than 10");
}

test();

使用上述选项之一运行将在 Remix 终端中显示结果

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

  • 模拟您的dapp前端将如何使用web3.js或ethers.js

  • 快速部署和与多个合约实例交互,而无需通过Remix GUI。

  • 对以前部署的合约运行一些测试。

部署合约的脚本

Remix接受异步/等待脚本来运行 web3.js 或者 ethers.js 命令。该脚本需要包装在自执行函数中。

设置

  1. 这些脚本需要访问合约的ABI。 ABI位于合约的元数据文件中。请确保通过转到设置模块并检查“生成合约元数据”选项是否已选中来创建此元数据文件。

  2. 编译Solidity文件-以生成合约元数据。

  3. 在Deploy & Run插件中,选择环境。

    • Async/await脚本适用于所有环境:Remix VM、Injected Provider(通常是MetaMask)和外部的HTTP Provider.。

文件浏览器中的JS脚本

工作区脚本文件夹中,有两个示例文件:一个使用web3.js,另一个使用ethers.js

编写合约并实时运行脚本

在开发合约时,通常在编译成功后运行脚本非常方便。

这样一来,人们可以快速部署和调用多个合约以将它们设置为所需的测试状态。

此外,如果脚本包含Mocha测试,也会运行这些测试。

为了实现这一点,请在合同中添加NatSpec标签@custom:dev-run-script,并跟随绝对文件路径,例如:

  /**
   * @title ContractName
   * @dev ContractDescription
   * @custom:dev-run-script file_path
   */
  contract ContractName {}

快捷键:在编辑Solidity文件时,按Ctrl+Shift+S将编译该文件并运行脚本。相比之下,按Ctrl+S仅会开始编译。

示例脚本

下面的示例部署了一个名为CustomERC20.sol的Solidity合约。该示例使用web3.js库,也可以使用Ethers.js。

有关此示例的更多信息,请参见:运行async/await脚本

(async () => {
  try {
    console.log('deploy...')

    // Note that the script needs the ABI which is generated from the compilation artifact.
    const metadata = JSON.parse(await remix.call('fileManager', 'getFile', 'browser/artifacts/CustomERC20.json'))
    const accounts = await web3.eth.getAccounts()

    let contract = new web3.eth.Contract(metadata.abi)

    contract = contract.deploy({
      data: metadata.data.bytecode.object,
      arguments: ["Mask", "N95"]
    })

    newContractInstance = await contract.send({
      from: accounts[0],
      gas: 1500000,
      gasPrice: '30000000000'
    })
    console.log(newContractInstance.options.address)
  } catch (e) {
    console.log(e.message)
  }
})()

欲了解更多脚本示例,请查看常见问题的脚本

Remix脚本中的require

require or importstatement is supported in a limited manner for Remix supported modules with Remix Scripts.

For now, modules supported by Remix are:

  • ethers

  • web3

  • swarmgw

  • chai

  • starknet

  • multihashes

  • zokrates-js

  • snarkjs

  • circomlibjs

  • @zk-kit/incremental-merkle-tree

  • @semaphore-protocol/proof

  • @semaphore-protocol/group

  • @semaphore-protocol/identity

  • @semaphore-protocol/data

  • @chainlink/functions-toolkit

  • @personaelabs/spartan-ecdsa

  • @ethereumjs/util

  • ffjavascript

  • sindri

  • remix

  • hardhat (only for hardhat.ethers object)

对于不支持的模块,将显示此错误信息:<module_name> 模块 require 不受 Remix IDE 支持。