Solidity - 输入 JSON 描述的 Solidity 代码

2024-03-15

我想编译我的以太坊 HelloWorld.sol 智能合约。在所有教程中,您都是这样做的:

var solc = require('solc');
var compiledContract = solc.compile(fs.readFileSync('HelloWorld.sol').toString();

其中 HelloWorld.sol 是:

pragma solidity ^0.5.1;

contract HelloWorld {
    bytes32 message;
    constructor(bytes32 myMessage) public {
        message = myMessage;
    }

    function getMessage() public view returns(bytes32){
        return message;
    }
}

换句话说,我将原始 Solidity 合约代码放入 solc.compile() 方法中。但是这个过程给了我这个错误compiledContract:

'{"errors":[{"component":"general","formattedMessage":"* Line 1, Column 1\\n  Syntax error: value, object or array expected.\\n* Line 1, Column 2\\n  Extra non-whitespace after JSON value.\\n","message":"* Line 1, Column 1\\n  Syntax error: value, object or array expected.\\n* Line 1, Column 2\\n  Extra non-whitespace after JSON value.\\n","severity":"error","type":"JSONError"}]}'

我寻找解决方案很长一段时间,但我唯一发现的是

“高级 API 由单一方法compile 组成,该方法 需要编译器标准输入和输出 JSON。”

(link https://github.com/ethereum/solc-js)。标准输入 JSON 看起来像是 JSON 和此 Solidity 代码的某种组合。所以我的问题是 -
如何将 Solidity 合约代码转换为编译器标准输入 JSON?
我是否正确,这是编写合同的唯一方法?


这段代码对我有用,index.js

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

const CONTRACT_FILE = 'HelloWorld.sol'

const content = fs.readFileSync(CONTRACT_FILE).toString()

const input = {
  language: 'Solidity',
  sources: {
    [CONTRACT_FILE]: {
      content: content
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*']
      }
    }
  }
}

const output = JSON.parse(solc.compile(JSON.stringify(input)))

for (const contractName in output.contracts[CONTRACT_FILE]) {
  console.log(output.contracts[CONTRACT_FILE][contractName].evm.bytecode.object)
}

HelloWorld.sol

contract HelloWorld {
    bytes32 message;
    constructor(bytes32 myMessage) public {
        message = myMessage;
    }

    function getMessage() public view returns(bytes32){
        return message;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Solidity - 输入 JSON 描述的 Solidity 代码 的相关文章

随机推荐