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

2023-11-01

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";必须要通过/=重新映射才起作用。如果有多个匹配,则选择具有最长公共前缀的进行匹配。

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

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

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

如果用选项--link调用Solc,则所有输入文件都被解释为未链接的二进制文件(HEX编码),在上面给出的__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":
      [
        "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": {
        "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" ]
      },
      // 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)
      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: {
              "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: ""
        }
      }
    }
  }
}
复制代码
  • 错误类型说明:
  1. JSONError:JSON错误,JSON输入不符合要求的格式,例如输入不是JSON对象,不支持语言,等等。
  2. IOError:IO错误,IO和导入处理错误,如提供的源中的不可解析URL或hash不匹配。
  3. ParserError:语法f分析错误,源代码不符合语言规则。
  4. DocstringParsingError:文档解析错误,无法解析注释块中的NATSPEC标记。
  5. SytRealError:语法错误,如continuefor循环之外使用。
  6. DeclarationError:声明错误,无效、不可解析或冲突的标识符名称。例如未找到标识符
  7. TypeError:类型错误,如无效类型转换、无效赋值等。
  8. UnimplementedFeatureError:编译器不支持该特性,但希望在将来的版本中得到支持。
  9. InternalCompilerError:编译器中触发内部错误,这应该作为一个问题来反馈。
  10. Exception:例外,编译过程中未知的故障,这应该作为一个问题反馈。
  11. CompilerError:编译错误,编译器堆栈的使用无效,这应该作为一个问题来反馈。
  12. FatalError:致命错误,这应该作为一个问题来反馈。
  13. Warning:警告并没有停止编译,但如果可能的话,应该加以处理。

原文请访问:solc

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

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

随机推荐

  • 无缝漫游的过程!

    无缝漫游中无线AP的配置与普通无线AP的配置基本相同 只是应当注意以下几个方面的问题 所有无线AP必须使用同一SSID 所有无线AP必须使用同一网段的IP地址 并且处于同一VLAN中 信号相互覆盖的无线AP不能使用相同的频道 由于多个AP信
  • 图形分析之Nsight的使用

    作者 i dovelemon 日期 2017 06 11 来源 CSDN 主题 Nsight OpenGL 引言 最开始的时候 我进行图形编程使用的是DX 所以那时候进行图形分析的时候 基本都是使用PIX 后来转向了OpenGL 分析的时候
  • JVM-17(垃圾回收器)上

    目录 17 1 GC分类与性能指标 17 1 1 JVM的发展 17 1 2评估GC的性能指标 17 2 不同的垃圾回收器概述 17 3 Serial回收器 串行回收 17 4 ParNew回收器 并行回收 17 5 Parallel回收器
  • html超链接打开共享文件夹,教你如何访问共享文件夹

    现在我们往往要讲究 资源共享 就是有好的东西跟大家一起分享 那么到电脑上呢经常有一些文件夹 有的是加密的 有的是共享的 今天呢小编就要给大家讲讲如何访问这些共享文件夹 要想查看共享文件夹其实也是有步骤可言的 首先 要先打开控制面板 有一个W
  • 电脑开机就显示360服务器,我用360给电脑杀毒,一直到开机启动项会停止,显示“扫面服务意外终止,无法继续扫描,这可能是由于程序...

    希望我的回答可以帮助楼主解决问题哦 这个问题很明显是杀毒软件自身的问题 不太知道诺顿这款杀毒软件 是不是在升级过程中发生什么问题造成的 楼主可以尝试换用腾讯电脑管家 这款杀毒软件在病毒以及木马的查杀方面很权威 很成熟 下面是我总结的电脑容易
  • ZGC收集器介绍

    ZGC收集器 XX UseZGC ZGC是一款JDK 11中新加入的具有实验性质的低延迟垃圾收集器 ZGC可以说源自于是Azul System公司开发的C4 Concurrent Continuously Compacting Collec
  • OK6410矩阵键盘驱动问题解决方案

    在嵌入式系统开发中 矩阵键盘是一种常见的输入设备 OK6410是一款广泛使用的ARM开发板 本文将介绍如何在OK6410开发板上实现矩阵键盘的驱动 硬件连接 首先 我们需要将矩阵键盘与OK6410开发板进行连接 矩阵键盘通常由多个行和列组成
  • ResNet到底在解决一个什么问题呢?

    点击上方 小白学视觉 选择加 星标 或 置顶 重磅干货 第一时间送达 来源 知乎 https www zhihu com question 64494691 文仅交流 侵删 ResNet发布于2015年 目前仍有大量CV任务用其作为back
  • C# 代码转化为Java代码

    http www tangiblesoftwaresolutions com Free Editions html Install Instant C converts VB NET code to C Install Instant VB
  • 史上最全midjourney关键词

    最全midjourney关键词 篇幅太长 文章最后有可编辑版本获取链接 增强图片真实感 清晰度 unreal engine 虚幻引擎 ultra realistic 超真实 photography 摄影图片 detailed 细节 4K 4
  • LaTeX 使用笔记——公式篇

    目录 一 行内公式 二 独立公式 一 行内公式 二 独立公式 一 括号 1 当括号的两边分别位于上下两行公式 且可能出现两个括号大小不一致的情况 例如 使用LaTeX代码 begin aligned dot V k v 1 z k v 1
  • 一次性搞清楚unicode、codepoint、代码点、UTF

    最近在处理字符过滤 重新研究了下字符 unicode和代码点的相关知识 首先要说一下编码的基本知识unicode unicode unicode是计算机科学领域里的一项业界标准 包括字符集 编码方案等 计算机采用八比特一个字节 一个字节最大
  • Python 爬虫获取某贴吧所有成员用户名

    最近想用Python爬虫搞搞百度贴吧的操作 所以我得把原来申请的小号找出来用 有一个小号我忘了具体ID 只记得其中几个字母以及某个加入的贴吧 所以今天就用爬虫来获取C语言贴吧的所有成员 计划很简单 爬百度贴吧的会员页面 把结果存到MySQL
  • FreeMarker模板使用方法讲解

    项目需要 刚接触 正在学习 FreeMarker简介 FreeMarker模板文件主要由如下4个部分组成 1 文本 直接输出的部分 2 注释 lt gt 格式部分 不会输出 3 插值 即 或 格式的部分 将使用数据模型中的部分替代输出 4
  • 深度学习之基于CNN实现汉字版手写数字识别(Chinese-Mnist)

    Mnist数据集是深度学习入门的数据集 昨天发现了Chinese Mnist数据集 与Mnist数据集类似 只不过是汉字数字 例如 一 二 三 等 本次实验利用自己搭建的CNN网络实现Chinese版的手写数字识别 1 导入库 import
  • C++疑难杂症 error LNK2001: 无法解析的外部符号

    问题简述 error LNK2001 无法解析的外部符号 private static int ETH m age m age ETH 0HA 这类问题是我们在编译过程很常见 原因我百度的时候发现也分好几种 有可能是没有包含相应的头文件 也
  • vue 用axios请求接口的使用以及配置

    若依框架前后端分离 用axios请求接口的使用以及配置 首先需要下载安装 cnpm install axios save 安装完成以后进行配置 打开main js import axios from axios Vue prototype
  • .NET静态代码检查工具StyleCop的安装与使用

    最近需要做一个C 项目的代码走查 其中的一项内容就是要用代码的静态分析工具对代码进行检测 我的想法是使用VisualStudio自带的Microsoft托管建议规则外加StyleCop工具检测问题 主要是警告 再对这些问题逐一分析 我使用的
  • cbm+soma+simm ibm的SOA实施方法论

    cbm soma simm ibm的SOA实施方法论http www ibm com developerworks cn webservices 0909 CBM SIMM SOMA soa
  • 如何通过solc编译solidity编写的以太坊智能合约

    solc solidity的编译器 solidity编写的以太坊智能合约可通过命令行编译工具solc来进行编译 成为以太坊虚拟机中的代码 solc编译后最终部署到链上形成我们所见到的各种智能合约 作为一个solidity命令行编译工具 我们