1.3.1 • Published 4 months ago

prettier-plugin-solidity v1.3.1

Weekly downloads
11,785
License
MIT
Repository
github
Last release
4 months ago

prettier-plugin-solidity

Telegram Twitter Follow GitPOAP Badge

A Prettier plugin for automatically formatting your Solidity code.

Installation and usage

Using in NodeJS

Install both prettier and prettier-plugin-solidity:

npm install --save-dev prettier prettier-plugin-solidity

Run prettier in your contracts:

npx prettier --write --plugin=prettier-plugin-solidity 'contracts/**/*.sol'

You can add a script for running prettier on all your contracts:

"prettier": "prettier --write --plugin=prettier-plugin-solidity 'contracts/**/*.sol'"

Or you can use it as part of your linting to check that all your code is prettified:

"lint": "prettier --list-different --plugin=prettier-plugin-solidity 'contracts/**/*.sol'"

Prettier Solidity only works with valid code. If there is a syntax error, nothing will be done and a parser error will be thrown.

Using in the Browser

Added in v1.1.0

To use this package in the browser, you need to load Prettier's standalone bundle before loading the build provided in this package.

<script src="https://unpkg.com/prettier@latest"></script>
<script src="https://unpkg.com/prettier-plugin-solidity@latest"></script>

Prettier's unpkg field points to https://unpkg.com/prettier/standalone.js, in a similar way this plugin points to https://unpkg.com/prettier-plugin-solidity/dist/standalone.js.

Once the scripts are loaded you will have access the globals prettier and prettierPlugins.

We follow Prettier's strategy for populating their plugins in the object prettierPlugins, you can load other plugins like https://unpkg.com/prettier@2.8.0/parser-markdown.js and Prettier will have access to multiple parsers.

<script>
  async function format(code) {
    return await prettier.format(code, {
      parser: 'solidity-parse',
      plugins: [solidityPlugin]
    });
  }

  const originalCode = 'contract Foo {}';
  const formattedCode = format(originalCode);
</script>

For more details and please have a look at Prettier's documentation.

Creating a package for the Browser

Added in v1.2.0

If you are creating your own package to be run in a browser, you might want to import the standalone files directly.

import prettier from 'prettier/standalone';
import solidityPlugin from 'prettier-plugin-solidity/standalone';

async function format(code) {
  return await prettier.format(code, {
    parser: "solidity-parse",
    plugins: [solidityPlugin],
  });
}

const originalCode = 'contract Foo {}';
const formattedCode = format(originalCode);

Configuration File

Prettier provides a flexible system to configure the formatting rules of a project. For more information please refer to the documentation. The following is the default configuration internally used by this plugin.

{
  "plugins": ["prettier-plugin-solidity"],
  "overrides": [
    {
      "files": "*.sol",
      "options": {
        "parser": "solidity-parse",
        "printWidth": 80,
        "tabWidth": 4,
        "useTabs": false,
        "singleQuote": false,
        "bracketSpacing": false,
      }
    }
  ]
}

Note the use of the overrides property which allows for multiple configurations in case there are other languages in the project (i.e. JavaScript, JSON, Markdown).

Since Prettier v3.0.0, the plugin search feature has been removed so we encourage adding our plugin to the configuration file.

Most options are described in Prettier's documentation.

Compiler

Many versions of the Solidity compiler have changes that affect how the code should be formatted. This plugin, by default, tries to format the code in the most compatible way that it's possible, but you can use the compiler option to nudge it in the right direction.

One example of this is import directives. Before 0.7.4, the compiler didn't accept multi-line import statements, so we always format them in a single line. But if you use the compiler option to indicate that you are using a version greater or equal than 0.7.4, the plugin will use multi-line imports when it makes sense.

The Solidity versions taken into consideration during formatting are:

  • v0.7.4: Versions prior 0.7.4 had a bug that would not interpret correctly imports unless they are formatted in a single line.

    // Input
    import { Foo as Bar } from "/an/extremely/long/location";
    
    // "compiler": undefined
    import { Foo as Bar } from "/an/extremely/long/location";
    
    // "compiler": "0.7.3" (or lesser)
    import { Foo as Bar } from "/an/extremely/long/location";
    
    // "compiler": "0.7.4" (or greater)
    import {
        Foo as Bar
    } from "/an/extremely/long/location";
  • v0.8.0: Introduced these changes

    • The type byte has been removed. It was an alias of bytes1.
    • Exponentiation is right associative, i.e., the expression a**b**c is parsed as a**(b**c). Before 0.8.0, it was parsed as (a**b)**c.
    // Input
    bytes1 public a;
    byte public b;
    
    uint public c = 1 ** 2 ** 3;
    
    // "compiler": undefined
    bytes1 public a;
    byte public b;
    
    uint public c = 1**2**3;
    
    // "compiler": "0.7.6" (or lesser)
    bytes1 public a;
    byte public b;
    
    uint public c = (1**2)**3;
    
    // "compiler": "0.8.0" (or greater)
    bytes1 public a;
    bytes1 public b;
    
    uint public c = 1**(2**3);

You might have a multi-version project, where different files are compiled with different compilers. If that's the case, you can use overrides to have a more granular configuration:

{
  "overrides": [
    {
      "files": "contracts/v1/**/*.sol",
      "options": {
        "compiler": "0.6.3"
      }
    },
    {
      "files": "contracts/v2/**/*.sol",
      "options": {
        "compiler": "0.8.4"
      }
    }
  ]
}
DefaultCLI OverrideAPI Override
None--compiler <string>compiler: "<string>"

Experimental Ternaries

Added in v1.3.0

Mimicking prettier's new ternary formatting for the community to try.

Valid options:

  • true - Use curious ternaries, with the question mark after the condition.
  • false - Retain the default behavior of ternaries; keep question marks on the same line as the consequent.
DefaultCLI OverrideAPI Override
false--experimental-ternariesexperimentalTernaries: <bool>

Integrations

Vim

To integrate this plugin with vim, first install vim-prettier. These instructions assume you are using vim-plug. Add this to your configuration:

Plug 'prettier/vim-prettier', {
  \ 'do': 'yarn install && yarn add prettier-plugin-solidity',
  \ 'for': [
    \ 'javascript',
    \ 'typescript',
    \ 'css',
    \ 'less',
    \ 'scss',
    \ 'json',
    \ 'graphql',
    \ 'markdown',
    \ 'vue',
    \ 'lua',
    \ 'php',
    \ 'python',
    \ 'ruby',
    \ 'html',
    \ 'swift',
    \ 'solidity'] }

We modified the do instruction to also install this plugin. Then you'll have to configure the plugin to always use the version installed in the vim plugin's directory. The vim-plug directory depends on value you use in call plug#begin('~/.vim/<dir>'):

let g:prettier#exec_cmd_path = '~/.vim/plugged/vim-prettier/node_modules/.bin/prettier'

To check that everything is working, open a Solidity file and run :Prettier.

If you also want to autoformat every time you write the buffer, add these lines:

let g:prettier#autoformat = 0
autocmd BufWritePre *.sol Prettier

Now Prettier will be run every time the file is saved.

VSCode

VSCode is not familiar with the Solidity language. There are 2 extensions that you can install to provide support for Solidity:

code --install-extension JuanBlanco.solidity
# or
code --install-extension NomicFoundation.hardhat-solidity

:warning: These 2 extensions offer similar functionality and will clash with each other: Please choose which one matches your projects better.

These extensions provide basic integration with Prettier; in most cases, no further action is needed.

Make sure your editor has format on save set to true. When you save VSCode will ask you what formatter would you like to use for the Solidity language, you can choose JuanBlanco.solidity or NomicFoundation.hardhat-solidity.

At this point VSCode's settings.json should have a configuration similar to this:

{
  "editor.formatOnSave": true,
  "solidity.formatter": "prettier", // This is the default so it might be missing.
  "[solidity]": {
    // "editor.defaultFormatter": "JuanBlanco.solidity"
    // "editor.defaultFormatter": "NomicFoundation.hardhat-solidity"
  }
}

If you want more control over other details, you should proceed to install prettier-vscode.

code --install-extension esbenp.prettier-vscode

To interact with 3rd party plugins, prettier-vscode will look in the project's npm modules, so you'll need to have prettier and prettier-plugin-solidity in your package.json

npm install --save-dev prettier prettier-plugin-solidity

This will allow you to specify the version of the plugin in case you want to use the latest version of the plugin or need to freeze the formatting since new versions of this plugin will implement tweaks on the possible formats.

You'll have to let VSCode what formatter you prefer. This can be done by opening the command palette and executing:

>Preferences: Configure Language Specific Settings...

# Select Language
solidity

Now VSCode's settings.json should have this:

{
  "editor.formatOnSave": true,
  "[solidity]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Note: By design, Prettier prioritizes a local over a global configuration. If you have a .prettierrc file in your project, your VSCode's default settings or rules in settings.json are ignored (prettier/prettier-vscode#1079).

Pnpm

To make Prettier Solidity work in your project, you have to add a .prettierrc file as shown here.

Then, if you are using VSCode, you also need to add this to your VSCode settings:

{
  "prettier.documentSelectors": ["**/*.sol"]
}

Edge cases

Prettier Solidity does its best to be pretty and consistent, but in some cases it falls back to doing things that are less than ideal.

Modifiers in constructors

Modifiers with no arguments are formatted with their parentheses removed, except for constructors. The reason for this is that Prettier Solidity cannot always tell apart a modifier from a base constructor. So modifiers in constructors are not modified. For example, this:

contract Foo is Bar {
  constructor() Bar() modifier1 modifier2() modifier3(42) {}

  function f() modifier1 modifier2() modifier3(42) {}
}

will be formatted as

contract Foo is Bar {
  constructor() Bar() modifier1 modifier2() modifier3(42) {}

  function f() modifier1 modifier2 modifier3(42) {}
}

Notice that the unnecessary parentheses in modifier2 were removed in the function but not in the constructor.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b feature/fooBar)
  3. Commit your changes (git commit -am 'Add some fooBar')
  4. All existing tests and coverage must pass (npm run test:all), if coverage drops below 100% add missing tests.
  5. Push to the branch (git push origin feature/fooBar)
  6. Create a new Pull Request

Who's using it?

These are some of the projects using Prettier Solidity:

License

Distributed under the MIT license. See LICENSE for more information.

conflux-sponsor-faucet@everything-registry/sub-chunk-2470@yfi/yearn-protocol-nodejsabi-to-sol@damnherzg/web3-blockchain@axelar-network/token-linker@defi.org/web3-candies@idecentralize/pulsareumanimicoc-sol@infinitebrahmanuniverse/nolb-prettccmp-contracts@hexcrypto/hexdex-oraclesembark-coverage@holyswap/hardhat-framework@animoca/ethereum-contracts-core_librarybugscantea@jacktanws/web3-kit@mathieu-bour/prettier-config@kangafinance/hardhat-framework@latticexyz/common@layerzerolabs/prettier-config-nextgelato-relay-testgelato-thirdweb-relay@dlsl/hardhat-markup@luckyfinance/hardhat-framework@luxdefi/hardhat@lightsohq/prettier@lightdotso/prettier@megabytelabs/prettier-configdms-store-purchase-server@llllvvuu/vscode-solidity-langservererc223eslint-config-conformanceeslint-conformance@mimic-fi/v1-contractsoz-custommymultisig-contractniacin-cliprettier-config-solidityprettier-config-sexy-modesupervaulttokenteasol-proxysol-replsolid-mustachesolidity-lssolidity-language-serversolhint-config-mimicsolsproninjin10stack-packerredstone-evm-connectorremix-prettierworld-contractvscode-solidity-serverwepublic-contracts@wen-protocol/propelaliquidautem@0xpropel/core@0xobelisk/aptos-common@0xobelisk/common@0xobelisk/sui-common@0xzebra/core@threesigmaxyz/zkauth-contracts@timeswap-labs/timeswap-v1-convenience@violinio/violin-vaults-contracts@tracer-protocol/contracts@solarity/hardhat-markupaxon-daemonaxon-protocol-cli@alpaca-finance/alpaca-money-market@alexlit/config-prettier@biconomy/ccmp-contracts@dx-gov-test/dxdao-contracts@enzymefinance/prettier-config-solidity@etherisc/gif@nori-dot-com/eslint-config-nori@remax-ide/core@remax-ide/extension-debug-adaptar@remax-ide/extension-formatter@remax-ide/extension-language-compiler@remax-ide/extension-language-server@safient/claimscustom-sol@kenshi.io/solidquery@ottodev/prettier-config@ourz/our-contracts@settlemint/enteth-contracts@sentrei/prettier@polycity/hardhat-framework@projectsophon/prettier-config
1.3.1

4 months ago

1.3.0

4 months ago

1.2.0

6 months ago

1.1.4-dev

6 months ago

1.1.3

1 year ago

1.1.2

1 year ago

1.0.0

1 year ago

1.0.0-rc.1

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.0-dev.24

2 years ago

1.0.0-beta.24

2 years ago

1.0.0-dev.23

2 years ago

1.0.0-dev.22

2 years ago

1.0.0-beta.20

2 years ago

1.0.0-dev.21

2 years ago

1.0.0-beta.19

2 years ago

1.0.0-beta.18

3 years ago

1.0.0-beta.17

3 years ago

1.0.0-beta.16

3 years ago

1.0.0-beta.15

3 years ago

1.0.0-beta.14

3 years ago

1.0.0-beta.12

3 years ago

1.0.0-beta.13

3 years ago

1.0.0-beta.11

3 years ago

1.0.0-beta.10

3 years ago

1.0.0-beta.9

3 years ago

1.0.0-beta.8

3 years ago

1.0.0-beta.7

3 years ago

1.0.0-beta.6

3 years ago

1.0.0-beta.5

3 years ago

1.0.0-beta.4

3 years ago

1.0.0-beta.3

3 years ago

1.0.0-beta.2

3 years ago

1.0.0-beta.1

3 years ago

1.0.0-alpha.60

3 years ago

1.0.0-alpha.59

4 years ago

1.0.0-alpha.58

4 years ago

1.0.0-alpha.57

4 years ago

1.0.0-alpha.56

4 years ago

1.0.0-alpha.55

4 years ago

1.0.0-alpha.54

4 years ago

1.0.0-alpha.53

4 years ago

1.0.0-alpha.52

4 years ago

1.0.0-alpha.51

4 years ago

1.0.0-alpha.50

4 years ago

1.0.0-alpha.49

4 years ago

1.0.0-alpha.48

4 years ago

1.0.0-alpha.47

4 years ago

1.0.0-alpha.46

4 years ago

1.0.0-alpha.45

4 years ago

1.0.0-alpha.44

4 years ago

1.0.0-alpha.43

4 years ago

1.0.0-alpha.42

4 years ago

1.0.0-alpha.41

4 years ago

1.0.0-alpha.40

4 years ago

1.0.0-alpha.39

4 years ago

1.0.0-alpha.38

4 years ago

1.0.0-alpha.37

4 years ago

1.0.0-alpha.36

4 years ago

1.0.0-alpha.35

4 years ago

1.0.0-alpha.34

5 years ago

1.0.0-alpha.33

5 years ago

1.0.0-alpha.32

5 years ago

1.0.0-alpha.31

5 years ago

1.0.0-alpha.30

5 years ago

1.0.0-alpha.29

5 years ago

1.0.0-alpha.28

5 years ago

1.0.0-alpha.27

5 years ago

1.0.0-alpha.26

5 years ago

1.0.0-alpha.25

5 years ago

1.0.0-alpha.24

5 years ago

1.0.0-alpha.23

5 years ago

1.0.0-alpha.22

5 years ago

1.0.0-alpha.21

5 years ago

1.0.0-alpha.20

5 years ago

1.0.0-alpha.19

5 years ago

1.0.0-alpha.18

5 years ago

1.0.0-alpha.17

5 years ago

1.0.0-alpha.16

5 years ago

1.0.0-alpha.15

5 years ago

1.0.0-alpha.14

5 years ago

1.0.0-alpha.13

5 years ago

1.0.0-alpha.12

5 years ago

1.0.0-alpha.11

5 years ago

1.0.0-alpha.10

5 years ago

1.0.0-alpha.9

6 years ago

1.0.0-alpha.8

6 years ago

1.0.0-alpha.7

6 years ago

1.0.0-alpha.6

6 years ago

1.0.0-alpha.5

6 years ago

1.0.0-alpha.4

6 years ago