Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Compiler in Solidity

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use the compiler in Solidity". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 using the command line compiler

Solc is one of the targets for building the Solidity source library, and it is the command line compiler for Solidity. You can use the solc-- help command to see an explanation of all its options. The compiler can generate a variety of outputs, ranging from simple binaries and assembly files to abstract syntax trees (parsing trees) used to estimate "gas" usage. If you only want to compile one file, you can run solc-- bin sourceFile.sol to generate binaries. If you want to get some more advanced output information through solc, you can save all the output to a separate folder with the command solc-o outputDirectory-- bin-- ast-- asm sourceFile.sol.

Before you deploy your contract, activate the optimizer while compiling using solc-optimize-bin sourceFile.sol. By default, the optimizer will optimize the contract for 200 runs. If you want to optimize for initial contract deployment and get the smallest output, set it to-runs=1. If you expect many transactions and don't care for higher deployment cost and output size, set-runs to a high number.

The command line compiler automatically reads and imports files from the file system, but it also supports path redirection through the prefix=path option. For example:

This essentially tells the compiler to search for all files that start with github.com/ethereum/dapp-bin/ in the / usr/local/lib/dapp-bin directory, and if the compiler cannot find such files, it will then read all the files in the / usr/local/lib/fallback directory (a null prefix means always a match). Solc does not read files from file systems located outside the redirect target and explicitly specified source files, so statements like import "/ etc/passwd"; such statements, the compiler will only try to load the / etc/passwd file into the root directory after you add the = / option.

If there are multiple matches under the redirect path, select the match with the longest common prefix.

For security reasons, the compiler restricts the directories it can access. The path to the source file (and its subdirectories) specified on the command line and the path defined by redirection can be used in the import statement, while others are rejected. Additional paths (and their subdirectories) can be configured through-- allow-paths / sample/path,/another/sample/path.

If your contract uses libraries, you will notice that the compiled hexadecimal bytecode contains a string like LibraryName__. When you use solc as a linker, it inserts the address of the library for you in the following cases: either add-libraries "Math:0x12345678901234567890 Heap:0xabcdef0123456" to the command line to provide the address for each library, or save these strings to a file (one library per line) and use the-- libraries fileName parameter.

If the-- link option is used when invoking the solc command, all input files are parsed to unlinked binary data (hexadecimal encoding) in the _ _ LibraryName____ format mentioned above, and linked in place. (if the input is read from stdin, the resulting data is written to stdout.) In this case, all options except-- libraries (including-o) are ignored.

If the-- standard-json option is used when calling the solc command, it parses the input on the standard input in JSON format and returns the output in JSON format on the standard output.

2 Compiler input and output JSON description

The JSON formats shown below are used by the compiler API and, of course, are available on solc. Some fields are optional (see comments), and they may change, but all changes should be backward compatible.

The compiler API requires input in JSON format and outputs the compilation results in JSON format.

Comments are not allowed and are used here for explanatory purposes only.

Enter description

{/ / required: source code languages, such as "Solidity", "serpent", "lll", "assembly", etc. Language: "Solidity", / / required sources: {/ / the key here is the "global" name of the source file, and other files (see below) "myFile.sol" can be introduced through remappings: {/ / optional: the kaccak256 hash value of the source file Can be used to validate content loaded through URL. "keccak256": "0x123...", / / required (unless the "content" field is declared): the URL that points to the source file. / / URL (s) is loaded sequentially, and the result is checked by the keccak256 hash value (if there is a keccak256) / / if the hash value does not match, or if no URL returns successfully, an exception is thrown. "urls": ["bzzr://56ab...", "ipfs://Qma...", "file:///tmp/path/to/file.sol"]}," mortal ": {/ / optional: the keccak256 hash value of the file" keccak256 ":" 0x234... " / / required (unless the "urls" field is declared): literal content of the source file "content": "contract mortal is owned {function kill () {if (msg.sender = = owner) selfdestruct (owner) } "}}, / / optional settings: {/ / optional: sort list of redirecting parameters remappings: [": g/dir "], / / optional: optimizer configuration optimizer: {/ / default is disabled enabled: true, / / optimize based on how many times you want to run the code. / / A smaller value can optimize the cost of initial deployment, while a higher value can optimize the use of high frequency. Runs: 200}, / / specifies the version of EVM to be compiled. Can affect code generation and type checking. The available version is: homestead,tangerineWhistle,spuriousDragon,byzantium,constantinople evmVersion: "byzantium", / / optional: metadata configuration metadata: {/ / literal content only, not available URLs (default is false) useLiteralContent: true}, / / the address of the library. If all the required libraries are not given here, it will result in different unlinked objects libraries: {/ / the outermost key is the name of the source file that uses these libraries. / / if redirection is used, these source files should match the global path after redirection / / if the name of the source file is empty, then all libraries are global references "myFile.sol": {"MyLib": "0x123123."} / / the following can be used to select the desired output. / / if this field is ignored, the compiler loads and does type checking, but does not produce any output except for errors. / / the key at the first level is the file name, and the second level is the contract name. If the contract name is empty, it is for the file itself (output). / / if the wildcard character * is used, it means all contracts. / / the available output types are as follows: / / abi-ABI / / ast-AST / / legacyAST of all source files-legacyAST / / devdoc-developer documentation (natspec) / / userdoc-user documentation (natspec) / / metadata-metadata / / ir-remove the new assembly case before syntax sugar (desugaring) for all source files Type / / evm.assembly-New assembly format after removal of syntax sugar (desugaring) / / evm.legacyAssembly-JSON old style assembly format / / evm.bytecode.object-bytecode object / / evm.bytecode.opcodes-op code list / / evm.bytecode.sourceMap-source code mapping (for debugging) / / evm.bytecode.linkReferences-link reference (if Is an unlinked object) / / evm.deployedBytecode*-deployed bytecode (with the same option as evm.bytecode) / / evm.methodIdentifiers-function hash list / / evm.gasEstimates-function gas estimate / / ewasm.wast-eWASM S-expressions format (atm is not supported) / / ewasm.wasm-eWASM binary format (does not support atm) / Please note If you use options such as `evm`, `evm.bytecode`, `ewasm`, all its sub-items will be selected as output. In addition, `*` can be used as a wildcard to request all content. / / outputSelection: {/ / generate metadata and bytecode output for each contract. "*": {"*": ["metadata", "evm.bytecode"]}, / / enables abi and opcodes output of "MyContract" contracts defined in the "def" file. "def": {"MyContract": ["abi" "evm.bytecode.opcodes"]}, / / generate source code mapping output for each contract "*": {"*": ["evm.bytecode.sourceMap"]}, / / generate legacyAST output for each file "*": {"legacyAST"]}

Output description

{/ / optional: if no error / warning is encountered, errors: [{/ / optional: location in the source file sourceLocation: {file: "sourceFile.sol", start: 0, end: 100], / / mandatory: error type, such as "TypeError", "InternalCompilerError", "Exception", etc. / / you can view the complete list of error types at the end of the text: type: "TypeError", / / mandatory: the component in which the error occurred, such as "general" Component such as "ewasm": "general", / / mandatory: the severity of the error ("error" or "warning") severity: "error", / / mandatory message: "Invalid keyword" / / optional: formatted message formattedMessage with error source location: "sourceFile.sol:100: Invalid keyword"}], / / the output at the file level is included. Limits / filtering can be set through outputSelection. Sources: {"sourceFile.sol": {/ / Identifier (for source code mapping) id: 1, / / AST object ast: {}, / / legacyAST object legacyAST: {}}, / / contract level output is included here. Limits / filtering can be set through outputSelection. Contracts: {"sourceFile.sol": {/ / if the language used does not have a contract name, this field should be left blank. "ContractName": {/ / the application binary interface (ABI) of the Ethernet Fong contract. If empty, represents an empty array. / / refer to https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI abi: [], / / refer to metadata output document (serialized JSON string) metadata: "{...}", / / user documentation (natspec) userdoc: {}, / / developer documentation (natspec) devdoc: {} / / Intermediate representation (string) ir: ", / / EVM related output evm: {/ / assembly (string) assembly:", / / old style assembly (object) legacyAssembly: {} / / bytecode and related details bytecode: {/ / bytecode of hexadecimal string object: "00fe", / / list of opcodes (string) opcodes: "", / / string of source code mapping. Please refer to the definition of source mapping sourceMap: ", / / if the information is given here, it means that this is an unlinked object linkReferences: {" libraryFile.sol ": {/ / bytecode bytecode offset When linking, replace 20 bytes of "Library1" from the specified location: [{start: 0 start length: 20}, {start: 200] Length: 20}]}, / / same layout as above deployedBytecode: {}, / / list of function hashes methodIdentifiers: {"delegate (address)": "5c19a95c"} / / function's gas estimate gasEstimates: {creation: {codeDepositCost: "420000", executionCost: "infinite", totalCost: "infinite"}, external: {"delegate (address)": "25000"} Internal: {"heavyLifting ()": "infinite"}, / / eWASM related output ewasm: {/ / S-expressions format wast: "", / / binary format (hexadecimal string) wasm: ""}

Error Typ

JSONError: JSON input does not conform to the required format, for example, the input is not a JSON object, an unsupported language, and so on.

IOError: IO and import handling errors, for example, containing unparsed URL or mismatched hash values in the supplied source.

ParserError: the source code does not conform to the language rules.

DocstringParsingError: the NatSpec tag in the comment block cannot be parsed.

SyntaxError: syntax error, for example, continue is used outside the for loop.

DeclarationError: invalid, unresolvable, or conflicting identifier names such as Identifier not found.

TypeError: errors within the type system, such as invalid type conversions, invalid assignments, etc.

UnimplementedFeatureError: this feature is not currently supported by the compiler, but is expected to be supported in future releases.

InternalCompilerError: internal error triggered in the compiler-this should be reported as an issue.

Exception: unknown failure during compilation-this should be reported as an issue.

CompilerError: invalid use of compiler stack-this should be reported as an issue.

FatalError: fatal errors were not handled correctly-this should be reported as an issue.

Warning: warning, compilation will not be stopped, but should be handled as much as possible.

This is the end of "how to use the compiler in Solidity". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report