主页 > imtoken制作冷钱包 > 如何通过solc编译solidity编写的以太坊智能合约

如何通过solc编译solidity编写的以太坊智能合约

imtoken制作冷钱包 2023-03-26 06:18:09

solc:solidity 编译器

solidity编写的以太坊智能合约可以通过命令行编译工具solc进行编译,成为以太坊虚拟机中的代码。 solc编译完成后,最终部署到链上,形成我们看到的各种智能合约。

作为solidity命令行编译工具,我们来看看官网是怎么说solc的。

solc的安装很简单:

npm install -g solc
//或者
npm install -g solc-cli
//或者
sudo apt-get install solc

看看安装完成后,solc --help,solc --help命令显示了所有的solc命令选项。 编译器可以生成各种输出,比如最终的二进制合约文件,语法树的组装,或者预估的gas成本等。solc --bin sourceFile.sol,可以编译输出一个名为sourceFile.sol的智能合约文件. 如果你想要 solc 的一些更丰富的输出变量,你可以使用 solc -o outputDirectory --bin --ast --asm sourceFile.sol。

您可以在部署以太坊智能合约之前使用 solc --optimize --bin sourceFile.sol 进行优化。 默认情况下,solc编译器会帮你优化200次。 也可以设置--runs=1,这样会以最小化的方式编译。 如果您想要多次交易并且不关心成本,那么您可以将其设置为您想要的次数:)。

命令行编译器会自动读取需要导入的文件,也可以使用prefix=path指定路径,例如:

solc github.com/ethereum/dapp-bin/=/usr/local/lib/dapp-bin/=/usr/local/lib/fallback file.sol

这样,编译器就会从指定目录github.com/ethereum/dapp-bin/下的/usr/local/lib/dapp-bin/目录开始搜索。 如果找不到该文件,它将查看 /usr/local/lib/ fallback。 Solc 只会读取你指定的两个路径,所以像 import "/etc/passwd"; 它必须通过 /= 重新映射才能工作。 如果有多个匹配以太坊api,则选择公共前缀最长的匹配。

出于安全原因,编译器限制了它可以访问的目录。 拒绝在命令行上指定的源文件(及其子目录)的路径以及在命令行上指定的路径以外的所有其他内容。 --allow-paths /sample/path, /another/sample/path 切换。

如果使用智能合约,您会注意到字节码包含 __LibraryName______ 的子字符串。 您可以将 solc 用作链接器,这意味着它将在这些点为您插入库地址。

您可以通过在命令中添加 libraries --libraries "Math:0x12345678901234567890 Heap:0xabcdef0123456" 来提供每个库的地址,或者使用文件中的描述字符串(每行一个库)并使用 --libraries fileName solc 运行。

如果使用选项 --link 调用 Solc以太坊api,所有输入文件都被解释为未链接的二进制文件(十六进制编码),采用上面给出的 __LibraryName____ 格式,链接到适当的地址(如果从 stdin 输入读取,它被写入 stdout) . 在这种情况下,除了库之外的所有选项都将被忽略(包括 -o)。

如果使用 --standard-json 调用 SOLC,它将采用标准 JSON 输入(如下所述)并返回 JSON 输出。

solc编译器输入输出JSON描述

这些 JSON 格式通过编译器 API 使用,可通过 SOLC 使用。 出于向后兼容的目的,内容都是可修改的,有些对象是可选的(如前所述)。

编译器的 API 接受 JSON 格式的输入,并以 JSON 格式输出编译结果。

请注意,不允许发表评论。 以下例子中的注解在官网都有标注,方便学习者更好的理解。

{
  // Required: Source code language, such as "Solidity", "serpent", "lll", "assembly", etc.
  language: "Solidity",
  // Required
  sources:
  {
    // The keys here are the "global" names of the source files,
    // imports can use other files via remappings (see below).
    "myFile.sol":
    {
      // Optional: keccak256 hash of the source file
      // It is used to verify the retrieved content if imported via URLs.
      "keccak256": "0x123...",
      // Required (unless "content" is used, see below): URL(s) to the source file.
      // URL(s) should be imported in this order and the result checked against the
      // keccak256 hash (if available). If the hash doesn't match or none of the
      // URL(s) result in success, an error should be raised.
      "urls":

以太坊api_以太经典和以太坊算力差别_以太坊为什么叫以太坊

[ "bzzr://56ab...", "ipfs://Qma...", "file:///tmp/path/to/file.sol" ] }, "mortal": { // Optional: keccak256 hash of the source file "keccak256": "0x234...", // Required (unless "urls" is used): literal contents of the source file "content": "contract mortal is owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } }" } }, // Optional settings: { // Optional: Sorted list of remappings remappings: [ ":g/dir" ], // Optional: Optimizer settings optimizer: { // disabled by default enabled: true, // Optimize for how many times you intend to run the code. // Lower values will optimize more for initial deployment cost, higher values will optimize more for high-frequency usage. runs: 200 }, evmVersion: "byzantium", // Version of the EVM to compile for. Affects type checking and code generation. Can be homestead, tangerineWhistle, spuriousDragon, byzantium or constantinople // Metadata settings (optional) metadata: { // Use only literal content and not URLs (false by default) useLiteralContent: true }, // Addresses of the libraries. If not all libraries are given here, it can result in unlinked objects whose output data is different. libraries: { // The top level key is the the name of the source file where the library is used. // If remappings are used, this source file should match the global path after remappings were applied. // If this key is an empty string, that refers to a global level. "myFile.sol": {

以太坊api_以太经典和以太坊算力差别_以太坊为什么叫以太坊

"MyLib": "0x123123..." } } // The following can be used to select desired outputs. // If this field is omitted, then the compiler loads and does type checking, but will not generate any outputs apart from errors. // The first level key is the file name and the second is the contract name, where empty contract name refers to the file itself, // while the star refers to all of the contracts. // // The available output types are as follows: // abi - ABI // ast - AST of all source files // legacyAST - legacy AST of all source files // devdoc - Developer documentation (natspec) // userdoc - User documentation (natspec) // metadata - Metadata // ir - New assembly format before desugaring // evm.assembly - New assembly format after desugaring // evm.legacyAssembly - Old-style assembly format in JSON // evm.bytecode.object - Bytecode object // evm.bytecode.opcodes - Opcodes list // evm.bytecode.sourceMap - Source mapping (useful for debugging) // evm.bytecode.linkReferences - Link references (if unlinked object) // evm.deployedBytecode* - Deployed bytecode (has the same options as evm.bytecode) // evm.methodIdentifiers - The list of function hashes // evm.gasEstimates - Function gas estimates // ewasm.wast - eWASM S-expressions format (not supported atm) // ewasm.wasm - eWASM binary format (not supported atm) // // Note that using a using `evm`, `evm.bytecode`, `ewasm`, etc. will select every // target part of that output. Additionally, `*` can be used as a wildcard to request everything. // outputSelection: { // Enable the metadata and bytecode outputs of every single contract. "*": { "*": [ "metadata", "evm.bytecode" ] }, // Enable the abi and opcodes output of MyContract defined in file def. "def": { "MyContract": [ "abi", "evm.bytecode.opcodes" ]

以太坊为什么叫以太坊_以太坊api_以太经典和以太坊算力差别

}, // Enable the source map output of every single contract. "*": { "*": [ "evm.bytecode.sourceMap" ] }, // Enable the legacy AST output of every single file. "*": { "": [ "legacyAST" ] } } } }

{
  // Optional: not present if no errors/warnings were encountered
  errors: [
    {
      // Optional: Location within the source file.
      sourceLocation: {
        file: "sourceFile.sol",
        start: 0,
        end: 100
      ],
      // Mandatory: Error type, such as "TypeError", "InternalCompilerError", "Exception", etc.
      // See below for complete list of types.
      type: "TypeError",
      // Mandatory: Component where the error originated, such as "general", "ewasm", etc.
      component: "general",
      // Mandatory ("error" or "warning")
      severity: "error",
      // Mandatory
      message: "Invalid keyword"
      // Optional: the message formatted with source location
      formattedMessage: "sourceFile.sol:100: Invalid keyword"
    }
  ],
  // This contains the file-level outputs. In can be limited/filtered by the outputSelection settings.
  sources: {
    "sourceFile.sol": {
      // Identifier (used in source maps)

以太经典和以太坊算力差别_以太坊api_以太坊为什么叫以太坊

id: 1, // The AST object ast: {}, // The legacy AST object legacyAST: {} } }, // This contains the contract-level outputs. It can be limited/filtered by the outputSelection settings. contracts: { "sourceFile.sol": { // If the language used has no contract names, this field should equal to an empty string. "ContractName": { // The Ethereum Contract ABI. If empty, it is represented as an empty array. // See https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI abi: [], // See the Metadata Output documentation (serialised JSON string) metadata: "{...}", // User documentation (natspec) userdoc: {}, // Developer documentation (natspec) devdoc: {}, // Intermediate representation (string) ir: "", // EVM-related outputs evm: { // Assembly (string) assembly: "", // Old-style assembly (object) legacyAssembly: {}, // Bytecode and related details. bytecode: { // The bytecode as a hex string. object: "00fe", // Opcodes list (string) opcodes: "", // The source mapping as a string. See the source mapping definition. sourceMap: "", // If given, this is an unlinked object. linkReferences: {

以太经典和以太坊算力差别_以太坊为什么叫以太坊_以太坊api

"libraryFile.sol": { // Byte offsets into the bytecode. Linking replaces the 20 bytes located there. "Library1": [ { start: 0, length: 20 }, { start: 200, length: 20 } ] } } }, // The same layout as above. deployedBytecode: { }, // The list of function hashes methodIdentifiers: { "delegate(address)": "5c19a95c" }, // Function gas estimates gasEstimates: { creation: { codeDepositCost: "420000", executionCost: "infinite", totalCost: "infinite" }, external: { "delegate(address)": "25000" }, internal: { "heavyLifting()": "infinite" } } }, // eWASM related outputs ewasm: { // S-expressions format wast: "", // Binary format (hex string) wasm: "" } } } } }