运行 Solidity 测试时意外的标记“[”

Unexpected token '[' when running Solidity test

我目前正在 运行 对我的 Solidity 合约进行 Mocha 测试,但它会抛出与编译器代码相关的错误。

C:\eth\compile.js:8
modules.exports = solc.compile(source).[];

SyntaxError: Unexpected token '['
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\eth\test\inbox.test.js:5:31)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.exports.requireOrImport (C:\eth\node_modules\mocha\lib\esm-utils.js:42:12)
    at Object.exports.loadFilesAsync (C:\eth\node_modules\mocha\lib\esm-utils.js:55:34)
    at Mocha.loadFilesAsync (C:\eth\node_modules\mocha\lib\mocha.js:473:19)
    at singleRun (C:\eth\node_modules\mocha\lib\cli\run-helpers.js:125:15)
    at exports.runMocha (C:\eth\node_modules\mocha\lib\cli\run-helpers.js:190:10)
    at Object.exports.handler (C:\eth\node_modules\mocha\lib\cli\run.js:362:11)
    at C:\eth\node_modules\mocha\node_modules\yargs\build\index.cjs:443:71

编译器本身是:

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');

modules.exports = solc.compile(source).[:Inbox];
  1. 您需要传递 JSON-stringified 选项对象(给 compile() 函数),而不仅仅是文本源。请参阅 readme.
  2. 中的示例
  3. 您的 solc.compile(source).[:Inbox] 代码存在语法错误(将对 属性 的访问与 . 以及数组与 [ 的访问相结合)和逻辑错误(未定义 :Inbox,编译结果的路径不正确,试图将 JSON 字符串作为对象访问)。

假设 inbox.sol 包含 contract Inbox 这是您要编译的主合约,这是您问题中最后一行的有效代码替换:

const options = {
  language: 'Solidity',
  sources: {
    'inbox.sol': {
      content: source
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*']
      }
    }
  }
};
const compiledRaw = solc.compile(JSON.stringify(options));
const compiledObj = JSON.parse(compiledRaw);
const compiledInboxContract = compiledObj.contracts['inbox.sol']['Inbox'];
//console.log(compiledInboxContract)
module.exports = compiledInboxContract;