代码风格指南¶

Introduction¶

This guide is intended to provide coding conventions for writing solidity code.This guide should be thought of as an evolving document that will change overtime as useful conventions are found and old conventions are rendered obsolete.

Many projects will implement their own style guides. In the event ofconflicts, project specific style guides take precedence.

The structure and many of the recommendations within this style guide weretaken from python’spep8 style guide.

The goal of this guide is not to be the right way or the best way to writesolidity code. The goal of this guide is consistency. A quote from python’spep8captures this concept well.

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.But most importantly: know when to be inconsistent – sometimes the style guide just doesn’t apply. When in doubt, use your best judgement. Look at other examples and decide what looks best. And don’t hesitate to ask!

Code Layout¶

Indentation¶

Use 4 spaces per indentation level.

Tabs or Spaces¶

Spaces are the preferred indentation method.

Mixing tabs and spaces should be avoided.

Blank Lines¶

Surround top level declarations in solidity source with two blank lines.

Yes:

  1. contract A {
  2. ...
  3. }
  4.  
  5.  
  6. contract B {
  7. ...
  8. }
  9.  
  10.  
  11. contract C {
  12. ...
  13. }

No:

  1. contract A {
  2. ...
  3. }
  4. contract B {
  5. ...
  6. }
  7.  
  8. contract C {
  9. ...
  10. }

Within a contract surround function declarations with a single blank line.

Blank lines may be omitted between groups of related one-liners (such as stub functions for an abstract contract)

Yes:

  1. contract A {
  2. function spam() public;
  3. function ham() public;
  4. }
  5.  
  6.  
  7. contract B is A {
  8. function spam() public {
  9. ...
  10. }
  11.  
  12. function ham() public {
  13. ...
  14. }
  15. }

No:

  1. contract A {
  2. function spam() public {
  3. ...
  4. }
  5. function ham() public {
  6. ...
  7. }
  8. }

Maximum Line Length¶

Keeping lines under the PEP 8 recommendation of 79 (or 99)characters helps readers easily parse the code.

Wrapped lines should conform to the following guidelines.

  • The first argument should not be attached to the opening parenthesis.
  • One, and only one, indent should be used.
  • Each argument should fall on its own line.
  • The terminating element, );, should be placed on the final line by itself.
    Function Calls

Yes:

  1. thisFunctionCallIsReallyLong(
  2. longArgument1,
  3. longArgument2,
  4. longArgument3
  5. );

No:

  1. thisFunctionCallIsReallyLong(longArgument1,
  2. longArgument2,
  3. longArgument3
  4. );
  5.  
  6. thisFunctionCallIsReallyLong(longArgument1,
  7. longArgument2,
  8. longArgument3
  9. );
  10.  
  11. thisFunctionCallIsReallyLong(
  12. longArgument1, longArgument2,
  13. longArgument3
  14. );
  15.  
  16. thisFunctionCallIsReallyLong(
  17. longArgument1,
  18. longArgument2,
  19. longArgument3
  20. );
  21.  
  22. thisFunctionCallIsReallyLong(
  23. longArgument1,
  24. longArgument2,
  25. longArgument3);

Assignment Statements

Yes:

  1. thisIsALongNestedMapping[being][set][to_some_value] = someFunction(
  2. argument1,
  3. argument2,
  4. argument3,
  5. argument4
  6. );

No:

  1. thisIsALongNestedMapping[being][set][to_some_value] = someFunction(argument1,
  2. argument2,
  3. argument3,
  4. argument4);

Event Definitions and Event Emitters

Yes:

  1. event LongAndLotsOfArgs(
  2. adress sender,
  3. adress recipient,
  4. uint256 publicKey,
  5. uint256 amount,
  6. bytes32[] options
  7. );
  8.  
  9. LongAndLotsOfArgs(
  10. sender,
  11. recipient,
  12. publicKey,
  13. amount,
  14. options
  15. );

No:

  1. event LongAndLotsOfArgs(adress sender,
  2. adress recipient,
  3. uint256 publicKey,
  4. uint256 amount,
  5. bytes32[] options);
  6.  
  7. LongAndLotsOfArgs(sender,
  8. recipient,
  9. publicKey,
  10. amount,
  11. options);

Source File Encoding¶

UTF-8 or ASCII encoding is preferred.

Imports¶

Import statements should always be placed at the top of the file.

Yes:

  1. import "owned";
  2.  
  3.  
  4. contract A {
  5. ...
  6. }
  7.  
  8.  
  9. contract B is owned {
  10. ...
  11. }

No:

  1. contract A {
  2. ...
  3. }
  4.  
  5.  
  6. import "owned";
  7.  
  8.  
  9. contract B is owned {
  10. ...
  11. }

Order of Functions¶

Ordering helps readers identify which functions they can call and to find the constructor and fallback definitions easier.

Functions should be grouped according to their visibility and ordered:

  • constructor
  • fallback function (if exists)
  • external
  • public
  • internal
  • private
    Within a grouping, place the constant functions last.

Yes:

  1. contract A {
  2. function A() public {
  3. ...
  4. }
  5.  
  6. function() public {
  7. ...
  8. }
  9.  
  10. // External functions
  11. // ...
  12.  
  13. // External functions that are constant
  14. // ...
  15.  
  16. // Public functions
  17. // ...
  18.  
  19. // Internal functions
  20. // ...
  21.  
  22. // Private functions
  23. // ...
  24. }

No:

  1. contract A {
  2.  
  3. // External functions
  4. // ...
  5.  
  6. // Private functions
  7. // ...
  8.  
  9. // Public functions
  10. // ...
  11.  
  12. function A() public {
  13. ...
  14. }
  15.  
  16. function() public {
  17. ...
  18. }
  19.  
  20. // Internal functions
  21. // ...
  22. }

Whitespace in Expressions¶

Avoid extraneous whitespace in the following situations:

Immediately inside parenthesis, brackets or braces, with the exception of single line function declarations.

Yes:

  1. spam(ham[1], Coin({name: "ham"}));

No:

  1. spam( ham[ 1 ], Coin( { name: "ham" } ) );

Exception:

  1. function singleLine() public { spam(); }

Immediately before a comma, semicolon:

Yes:

  1. function spam(uint i, Coin coin) public;

No:

  1. function spam(uint i , Coin coin) public ;

More than one space around an assignment or other operator to align with
another:

Yes:

  1. x = 1;
  2. y = 2;
  3. long_variable = 3;

No:

  1. x = 1;
  2. y = 2;
  3. long_variable = 3;

Don’t include a whitespace in the fallback function:

Yes:

  1. function() public {
  2. ...
  3. }

No:

  1. function () public {
  2. ...
  3. }

Control Structures¶

The braces denoting the body of a contract, library, functions and structsshould:

  • open on the same line as the declaration
  • close on their own line at the same indentation level as the beginning of thedeclaration.
  • The opening brace should be proceeded by a single space.
    Yes:
  1. contract Coin {
  2. struct Bank {
  3. address owner;
  4. uint balance;
  5. }
  6. }

No:

  1. contract Coin
  2. {
  3. struct Bank {
  4. address owner;
  5. uint balance;
  6. }
  7. }

The same recommendations apply to the control structures if, else, while,and for.

Additionally there should be a single space between the control structuresif, while, and for and the parenthetic block representing theconditional, as well as a single space between the conditional parentheticblock and the opening brace.

Yes:

  1. if (...) {
  2. ...
  3. }
  4.  
  5. for (...) {
  6. ...
  7. }

No:

  1. if (...)
  2. {
  3. ...
  4. }
  5.  
  6. while(...){
  7. }
  8.  
  9. for (...) {
  10. ...;}

For control structures whose body contains a single statement, omitting thebraces is ok if the statement is contained on a single line.

Yes:

  1. if (x < 10)
  2. x += 1;

No:

  1. if (x < 10)
  2. someArray.push(Coin({
  3. name: 'spam',
  4. value: 42
  5. }));

For if blocks which have an else or else if clause, the else should beplaced on the same line as the if’s closing brace. This is an exception comparedto the rules of other block-like structures.

Yes:

  1. if (x < 3) {
  2. x += 1;
  3. } else if (x > 7) {
  4. x -= 1;
  5. } else {
  6. x = 5;
  7. }
  8.  
  9.  
  10. if (x < 3)
  11. x += 1;
  12. else
  13. x -= 1;

No:

  1. if (x < 3) {
  2. x += 1;
  3. }
  4. else {
  5. x -= 1;
  6. }

Function Declaration¶

For short function declarations, it is recommended for the opening brace of thefunction body to be kept on the same line as the function declaration.

The closing brace should be at the same indentation level as the functiondeclaration.

The opening brace should be preceded by a single space.

Yes:

  1. function increment(uint x) public pure returns (uint) {
  2. return x + 1;
  3. }
  4.  
  5. function increment(uint x) public pure onlyowner returns (uint) {
  6. return x + 1;
  7. }

No:

  1. function increment(uint x) public pure returns (uint)
  2. {
  3. return x + 1;
  4. }
  5.  
  6. function increment(uint x) public pure returns (uint){
  7. return x + 1;
  8. }
  9.  
  10. function increment(uint x) public pure returns (uint) {
  11. return x + 1;
  12. }
  13.  
  14. function increment(uint x) public pure returns (uint) {
  15. return x + 1;}

You should explicitly label the visibility of all functions, including constructors.

Yes:

  1. function explicitlyPublic(uint val) public {
  2. doSomething();
  3. }

No:

  1. function implicitlyPublic(uint val) {
  2. doSomething();
  3. }

The visibility modifier for a function should come before any custommodifiers.

Yes:

  1. function kill() public onlyowner {
  2. selfdestruct(owner);
  3. }

No:

  1. function kill() onlyowner public {
  2. selfdestruct(owner);
  3. }

For long function declarations, it is recommended to drop each argument ontoit’s own line at the same indentation level as the function body. The closingparenthesis and opening bracket should be placed on their own line as well atthe same indentation level as the function declaration.

Yes:

  1. function thisFunctionHasLotsOfArguments(
  2. address a,
  3. address b,
  4. address c,
  5. address d,
  6. address e,
  7. address f
  8. )
  9. public
  10. {
  11. doSomething();
  12. }

No:

  1. function thisFunctionHasLotsOfArguments(address a, address b, address c,
  2. address d, address e, address f) public {
  3. doSomething();
  4. }
  5.  
  6. function thisFunctionHasLotsOfArguments(address a,
  7. address b,
  8. address c,
  9. address d,
  10. address e,
  11. address f) public {
  12. doSomething();
  13. }
  14.  
  15. function thisFunctionHasLotsOfArguments(
  16. address a,
  17. address b,
  18. address c,
  19. address d,
  20. address e,
  21. address f) public {
  22. doSomething();
  23. }

If a long function declaration has modifiers, then each modifier should bedropped to its own line.

Yes:

  1. function thisFunctionNameIsReallyLong(address x, address y, address z)
  2. public
  3. onlyowner
  4. priced
  5. returns (address)
  6. {
  7. doSomething();
  8. }
  9.  
  10. function thisFunctionNameIsReallyLong(
  11. address x,
  12. address y,
  13. address z,
  14. )
  15. public
  16. onlyowner
  17. priced
  18. returns (address)
  19. {
  20. doSomething();
  21. }

No:

  1. function thisFunctionNameIsReallyLong(address x, address y, address z)
  2. public
  3. onlyowner
  4. priced
  5. returns (address) {
  6. doSomething();
  7. }
  8.  
  9. function thisFunctionNameIsReallyLong(address x, address y, address z)
  10. public onlyowner priced returns (address)
  11. {
  12. doSomething();
  13. }
  14.  
  15. function thisFunctionNameIsReallyLong(address x, address y, address z)
  16. public
  17. onlyowner
  18. priced
  19. returns (address) {
  20. doSomething();
  21. }

Multiline output parameters and return statements should follow the same style recommended for wrapping long lines found in the Maximum Line Length section.

Yes:

  1. function thisFunctionNameIsReallyLong(
  2. address a,
  3. address b,
  4. address c
  5. )
  6. public
  7. returns (
  8. address someAddressName,
  9. uint256 LongArgument,
  10. uint256 Argument
  11. )
  12. {
  13. doSomething()
  14.  
  15. return (
  16. veryLongReturnArg1,
  17. veryLongReturnArg2,
  18. veryLongReturnArg3
  19. );
  20. }

No:

  1. function thisFunctionNameIsReallyLong(
  2. address a,
  3. address b,
  4. address c
  5. )
  6. public
  7. returns (address someAddressName,
  8. uint256 LongArgument,
  9. uint256 Argument)
  10. {
  11. doSomething()
  12.  
  13. return (veryLongReturnArg1,
  14. veryLongReturnArg1,
  15. veryLongReturnArg1);
  16. }

For constructor functions on inherited contracts whose bases require arguments,it is recommended to drop the base constructors onto new lines in the samemanner as modifiers if the function declaration is long or hard to read.

Yes:

  1. contract A is B, C, D {
  2. function A(uint param1, uint param2, uint param3, uint param4, uint param5)
  3. B(param1)
  4. C(param2, param3)
  5. D(param4)
  6. public
  7. {
  8. // do something with param5
  9. }
  10. }

No:

  1. contract A is B, C, D {
  2. function A(uint param1, uint param2, uint param3, uint param4, uint param5)
  3. B(param1)
  4. C(param2, param3)
  5. D(param4)
  6. public
  7. {
  8. // do something with param5
  9. }
  10. }
  11.  
  12. contract A is B, C, D {
  13. function A(uint param1, uint param2, uint param3, uint param4, uint param5)
  14. B(param1)
  15. C(param2, param3)
  16. D(param4)
  17. public {
  18. // do something with param5
  19. }
  20. }

When declaring short functions with a single statement, it is permissible to do it on a single line.

Permissible:

  1. function shortFunction() public { doSomething(); }

These guidelines for function declarations are intended to improve readability.Authors should use their best judgement as this guide does not try to cover allpossible permutations for function declarations.

Mappings¶

TODO

Variable Declarations¶

Declarations of array variables should not have a space between the type andthe brackets.

Yes:

  1. uint[] x;

No:

  1. uint [] x;

Other Recommendations¶

  • Strings should be quoted with double-quotes instead of single-quotes.
    Yes:
  1. str = "foo";
  2. str = "Hamlet says, 'To be or not to be...'";

No:

  1. str = 'bar';
  2. str = '"Be yourself; everyone else is already taken." -Oscar Wilde';
  • Surround operators with a single space on either side.
    Yes:
  1. x = 3;
  2. x = 100 / 10;
  3. x += 3 + 4;
  4. x |= y && z;

No:

  1. x=3;
  2. x = 100/10;
  3. x += 3+4;
  4. x |= y&&z;
  • Operators with a higher priority than others can exclude surroundingwhitespace in order to denote precedence. This is meant to allow forimproved readability for complex statement. You should always use the sameamount of whitespace on either side of an operator:
    Yes:
  1. x = 2**3 + 5;
  2. x = 2*y + 3*z;
  3. x = (a+b) * (a-b);

No:

  1. x = 2** 3 + 5;
  2. x = y+z;
  3. x +=1;

Naming Conventions¶

Naming conventions are powerful when adopted and used broadly. The use ofdifferent conventions can convey significant meta information that wouldotherwise not be immediately available.

The naming recommendations given here are intended to improve the readability,and thus they are not rules, but rather guidelines to try and help convey themost information through the names of things.

Lastly, consistency within a codebase should always supercede any conventionsoutlined in this document.

Naming Styles¶

To avoid confusion, the following names will be used to refer to differentnaming styles.

  • b (single lowercase letter)
  • B (single uppercase letter)
  • lowercase
  • lower_case_with_underscores
  • UPPERCASE
  • UPPER_CASE_WITH_UNDERSCORES
  • CapitalizedWords (or CapWords)
  • mixedCase (differs from CapitalizedWords by initial lowercase character!)
  • Capitalized_Words_With_Underscores

Note

When using initialisms in CapWords, capitalize all the letters of the initialisms. Thus HTTPServerError is better than HttpServerError. When using initialisms is mixedCase, capitalize all the letters of the initialisms, except keep the first one lower case if it is the beginning of the name. Thus xmlHTTPRequest is better than XMLHTTPRequest.

Names to Avoid¶

  • l - Lowercase letter el
  • O - Uppercase letter oh
  • I - Uppercase letter eye
    Never use any of these for single letter variable names. They are oftenindistinguishable from the numerals one and zero.

Contract and Library Names¶

Contracts and libraries should be named using the CapWords style. Examples: SimpleToken, SmartBank, CertificateHashRepository, Player.

Struct Names¶

Structs should be named using the CapWords style. Examples: MyCoin, Position, PositionXY.

Event Names¶

Events should be named using the CapWords style. Examples: Deposit, Transfer, Approval, BeforeTransfer, AfterTransfer.

Function Names¶

Functions other than constructors should use mixedCase. Examples: getBalance, transfer, verifyOwner, addMember, changeOwner.

Function Argument Names¶

Function arguments should use mixedCase. Examples: initialSupply, account, recipientAddress, senderAddress, newOwner.

When writing library functions that operate on a custom struct, the structshould be the first argument and should always be named self.

Local and State Variable Names¶

Use mixedCase. Examples: totalSupply, remainingSupply, balancesOf, creatorAddress, isPreSale, tokenExchangeRate.

Constants¶

Constants should be named with all capital letters with underscores separatingwords. Examples: MAXBLOCKS, _TOKEN_NAME, TOKEN_TICKER, CONTRACT_VERSION.

Modifier Names¶

Use mixedCase. Examples: onlyBy, onlyAfter, onlyDuringThePreSale.

Enums¶

Enums, in the style of simple type declarations, should be named using the CapWords style. Examples: TokenGroup, Frame, HashStyle, CharacterLocation.

Avoiding Naming Collisions¶

  • singletrailing_underscore
    This convention is suggested when the desired name collides with that of abuilt-in or otherwise reserved name.

General Recommendations¶

TODO

原文: http://solidity.apachecn.org/cn/doc/v0.4.21/style-guide.html