├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github └── workflows │ ├── pull_requests.yml │ ├── release.yml │ └── tests.yml ├── .gitignore ├── .prettierrc ├── .releaserc ├── LICENSE ├── README.md ├── contracts ├── MockContract.sol └── MockNestedContract.sol ├── hardhat.config.ts ├── package-lock.json ├── package.json ├── src ├── common │ ├── constants.ts │ └── enums.ts ├── error-decoder.ts ├── errors │ ├── handlers.ts │ ├── panic.ts │ └── results.ts ├── index.ts └── types.ts ├── test └── index.test.ts ├── tsconfig.json └── tsconfig.release.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | trim_trailing_whitespace = true 7 | insert_final_newline = true 8 | 9 | [*.md] 10 | insert_final_newline = false 11 | trim_trailing_whitespace = false 12 | 13 | [*.{js,json,ts,mts,yml,yaml}] 14 | indent_size = 2 15 | indent_style = space 16 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | /**/*.js 2 | /dist 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "es6": true, 5 | "node": true 6 | }, 7 | "parser": "@typescript-eslint/parser", 8 | "parserOptions": { 9 | "project": "tsconfig.json", 10 | "sourceType": "module", 11 | "ecmaVersion": 2020 12 | }, 13 | "plugins": ["@typescript-eslint"], 14 | "extends": [ 15 | "eslint:recommended", 16 | "plugin:@typescript-eslint/recommended", 17 | "prettier" 18 | ], 19 | "rules": { 20 | // The following rule is enabled only to supplement the inline suppression 21 | // examples, and because it is not a recommended rule, you should either 22 | // disable it, or understand what it enforces. 23 | // https://typescript-eslint.io/rules/explicit-function-return-type/ 24 | "@typescript-eslint/explicit-function-return-type": "warn" 25 | }, 26 | "ignorePatterns": ["**/*.js", "**/*.d.ts", "typechain-types/**/*"] 27 | } 28 | -------------------------------------------------------------------------------- /.github/workflows/pull_requests.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | pull_request: 4 | 5 | name: 'Pull Request' 6 | 7 | jobs: 8 | tests: 9 | name: 'Lint and Tests' 10 | uses: ./.github/workflows/tests.yml 11 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | - beta 6 | - +([0-9])?(.{+([0-9]),x}).x 7 | 8 | name: 'Release' 9 | 10 | jobs: 11 | tests: 12 | name: 'Lint and Tests' 13 | uses: ./.github/workflows/tests.yml 14 | 15 | release: 16 | name: 'Publish Release' 17 | needs: [tests] 18 | runs-on: 'ubuntu-latest' 19 | steps: 20 | - uses: actions/checkout@v3 21 | - uses: actions/setup-node@v3 22 | with: 23 | cache: npm 24 | node-version: 16 25 | - run: npm ci --no-audit 26 | - run: npm run build 27 | - uses: codfish/semantic-release-action@v2 28 | id: semantic 29 | env: 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 31 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 32 | - name: 'Output new release version' 33 | if: steps.semantic.outputs.new-release-published == 'true' 34 | run: | 35 | echo "## New Release Published" >> $GITHUB_STEP_SUMMARY 36 | echo "🎉 ${{ steps.semantic.outputs.release-version }}" >> $GITHUB_STEP_SUMMARY 37 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_call: 3 | 4 | name: 'Tests' 5 | 6 | jobs: 7 | tests: 8 | name: 'Pull Request Checks' 9 | runs-on: 'ubuntu-latest' 10 | steps: 11 | - name: 'Check out the repo' 12 | uses: actions/checkout@v3 13 | 14 | - name: 'Install Node.js' 15 | uses: actions/setup-node@v3 16 | with: 17 | cache: npm 18 | node-version: 16 19 | 20 | - name: 'Install the dependencies' 21 | run: npm ci --no-audit 22 | 23 | - name: 'Lint the code' 24 | run: npm run lint 25 | 26 | - name: 'Add lint summary' 27 | run: | 28 | echo "## Lint results" >> $GITHUB_STEP_SUMMARY 29 | echo "✅ Passed" >> $GITHUB_STEP_SUMMARY 30 | 31 | - name: 'Run tests' 32 | run: npm run test 33 | 34 | - name: 'Test run build' 35 | run: npm run build 36 | 37 | - name: 'Add test summary' 38 | run: | 39 | echo "## Build results" >> $GITHUB_STEP_SUMMARY 40 | echo "✅ Passed" >> $GITHUB_STEP_SUMMARY 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Dependencies 7 | node_modules/ 8 | 9 | # Coverage 10 | coverage 11 | 12 | # Transpiled files 13 | build/ 14 | 15 | # VS Code 16 | .vscode 17 | !.vscode/tasks.js 18 | 19 | # JetBrains IDEs 20 | .idea/ 21 | 22 | # Optional npm cache directory 23 | .npm 24 | 25 | # Optional eslint cache 26 | .eslintcache 27 | 28 | # Misc 29 | .DS_Store 30 | 31 | dist/ 32 | typechain-types/ 33 | artifacts/ 34 | cache/ 35 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "printWidth": 100, 5 | "tabWidth": 2, 6 | "bracketSpacing": true, 7 | "semi": false 8 | } 9 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branches": [ 3 | "+([0-9])?(.{+([0-9]),x}).x", 4 | "main", 5 | "next", 6 | "next-major", 7 | { 8 | "name": "beta", 9 | "prerelease": true 10 | }, 11 | { 12 | "name": "alpha", 13 | "prerelease": true 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ethers-decode-error 2 | 3 | [![Release][gha-badge]][gha-ci] [![TypeScript version][ts-badge]][typescript-5-0] 4 | [![License: Apache 2.0][license-badge]][license] 5 | 6 | [gha-ci]: https://github.com/superical/ethers-decode-error/actions/workflows/release.yml 7 | [gha-badge]: https://github.com/superical/ethers-decode-error/actions/workflows/release.yml/badge.svg 8 | [ts-badge]: https://img.shields.io/badge/TypeScript-5.0-blue.svg 9 | [typescript-5-0]: https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/ 10 | [license-badge]: https://img.shields.io/badge/license-Apache_2.0-blue.svg 11 | [license]: https://github.com/superical/ethers-decode-error/blob/main/LICENSE 12 | 13 | For those who've grappled with extracting the actual error message or reason from the JSON RPC when a transaction fails 14 | or a smart contract reverts, you'll certainly appreciate how cumbersome it could at times. 15 | 16 | This is a simple utility library to help simplify the process of determining the actual errors from smart contract. You simply pass in the error object and you will get the actual error message and a bunch of other information about the error. It works with the regular revert errors, panic errors, Metamask rejection error and custom 17 | errors. 18 | 19 | ## Installation 20 | 21 | ```bash 22 | npm install ethers-decode-error --save 23 | ``` 24 | 25 | You will need to install ethers.js in your project if you have not: 26 | 27 | ```bash 28 | npm install ethers@^6 --save 29 | ``` 30 | 31 | > 💡 If you wish to use it with ethers v5 instead, you may want to refer to [v1](../../tree/1.x). 32 | 33 | ## Usage 34 | 35 | This library decodes an ethers error object reverted from a smart contract into results that lets you decide the best course of action from there. 36 | 37 | Start by creating an instance of the `ErrorDecoder`: 38 | 39 | ```typescript 40 | import { ErrorDecoder } from 'ethers-decode-error' 41 | 42 | const errorDecoder = ErrorDecoder.create() 43 | ``` 44 | 45 | The `create` method optionally accepts an array of ABI or contract interface objects as its first argument. Although the ABI is not required for regular reverts, it's recommended to supply the ABI or contract interfaces if you're expecting custom errors. See the examples in [Custom Error ABI and Interfaces](#custom-error-abi-and-interfaces) section for more details. 46 | 47 | After creating the instance, you can reuse the `decode` method throughout your code to handle any errors thrown when interacting with smart contracts: 48 | 49 | ```typescript 50 | import type { DecodedError } from 'ethers-decode-error' 51 | 52 | try { 53 | // Send a transaction that will revert 54 | } catch (err) { 55 | const decodedError: DecodedError = await errorDecoder.decode(err) 56 | console.log(`Revert reason: ${decodedError.reason}`) 57 | } 58 | ``` 59 | 60 | ### Decoded Error 61 | 62 | The `DecodedError` object is the result of the decoded error, which contains the following properties for handling the error occurred: 63 | 64 | | Property | Value Type | Remarks | 65 | | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 66 | | `type` | `ErrorType` | The type of the error. See [Error Types](#error-types). | 67 | | `reason` | `string \| null` | The decoded error message, or `null` if error is unknown or has no message. | 68 | | `data` | `string \| null` | The raw data bytes returned from the contract error, or `null` if error is unknown or empty. | 69 | | `args` | `Array` | The parameter values of the error if exists. For custom errors, the `args` will always be empty if no ABI or interface is supplied for decoding. | 70 | | `name` | `string \| null` | The name of the error. This can be used to identify the custom error emitted. If no ABI is supplied for custom error, this will be the selector hex. If error is `RpcError`, this will be the error code. `null` if error is `EmptyError`. | 71 | | `selector` | `string \| null` | The hexidecimal value of the selector. `null` if error is `EmptyError`. | 72 | | `signature` | `string \| null` | The signature of the error. `null` if error is `EmptyError` or no specified ABI for custom error. | 73 | | `fragment` | `string \| null` | The ABI fragment of the error. `null` if error is `EmptyError` or no specified ABI for custom error. | 74 | 75 | ### Error Types 76 | 77 | These are the possible `ErrorType` that could be returned as the `type` property in the `DecodedError` object: 78 | 79 | | Type | Description | 80 | | --------------------------- | ----------------------------------------- | 81 | | `ErrorType.EmptyError` | Contract reverted without reason provided | 82 | | `ErrorType.RevertError` | Contract reverted with reason provided | 83 | | `ErrorType.PanicError` | Contract reverted due to a panic error | 84 | | `ErrorType.CustomError` | Contract reverted due to a custom error | 85 | | `ErrorType.UserRejectError` | User rejected the transaction | 86 | | `ErrorType.RpcError` | An error from the JSON RPC | 87 | | `ErrorType.UnknownError` | An unknown error was thrown | 88 | 89 | ## Examples 90 | 91 | ### Revert/Require Errors 92 | 93 | ```typescript 94 | import { ErrorDecoder } from 'ethers-decode-error' 95 | 96 | const errorDecoder = ErrorDecoder.create() 97 | 98 | const WETH = new ethers.Contract('0xC02aa...756Cc2', abi, provider) 99 | try { 100 | const tx = await WETH.transfer('0x0', amount) 101 | await tx.wait() 102 | } catch (err) { 103 | const { reason, type } = await errorDecoder.decode(err) 104 | 105 | // Prints "ERC20: transfer to the zero address" 106 | console.log('Revert reason:', reason) 107 | // Prints "true" 108 | console.log(type === ErrorType.RevertError) 109 | } 110 | ``` 111 | 112 | ### Panic Errors 113 | 114 | ```typescript 115 | import { ErrorDecoder } from 'ethers-decode-error' 116 | 117 | const errorDecoder = ErrorDecoder.create() 118 | 119 | const OverflowContract = new ethers.Contract('0x12345678', abi, provider) 120 | try { 121 | const tx = await OverflowContract.add(123) 122 | await tx.wait() 123 | } catch (err) { 124 | const { reason, type } = await errorDecoder.decode(err) 125 | 126 | // Prints "Arithmetic operation underflowed or overflowed outside of an unchecked block" 127 | console.log('Panic message:', reason) 128 | // Prints "true" 129 | console.log(type === ErrorType.PanicError) 130 | } 131 | ``` 132 | 133 | ### Custom Errors 134 | 135 | ```typescript 136 | import { ErrorDecoder } from 'ethers-decode-error' 137 | import type { DecodedError } from 'ethers-decode-error' 138 | 139 | const abi = [ 140 | { 141 | inputs: [ 142 | { 143 | internalType: 'address', 144 | name: 'token', 145 | type: 'address', 146 | }, 147 | ], 148 | name: 'InvalidSwapToken', 149 | type: 'error', 150 | }, 151 | ] 152 | const errorDecoder = ErrorDecoder.create([abi]) 153 | 154 | const MyCustomErrorContract = new ethers.Contract('0x12345678', abi, provider) 155 | try { 156 | const tx = await MyCustomErrorContract.swap('0xabcd', 123) 157 | await tx.wait() 158 | } catch (err) { 159 | const decodedError = await errorDecoder.decode(err) 160 | const reason = customReasonMapper(decodedError) 161 | 162 | // Prints "Invalid swap with token contract address 0xabcd." 163 | console.log('Custom error reason:', reason) 164 | // Prints "true" 165 | console.log(type === ErrorType.CustomError) 166 | } 167 | 168 | const customReasonMapper = ({ name, args, reason }: DecodedError): string => { 169 | switch (name) { 170 | case 'InvalidSwapToken': 171 | // You can access the error parameters using their index: 172 | return `Invalid swap with token contract address ${args[0]}.` 173 | // Or, you could also access the error parameters using their names: 174 | return `Invalid swap with token contract address ${args['token']}.` 175 | 176 | // You can map any other custom errors here 177 | 178 | default: 179 | // This handles the non-custom errors 180 | return reason ?? 'An error has occurred' 181 | } 182 | } 183 | ``` 184 | 185 | #### Custom Error ABI and Interfaces 186 | 187 | Although the ABI or ethers `Interface` object of the contract is not required when decoding normal revert errors, it is recommended to provide it if you're expecting custom errors. This is because the ABI or `Interface` object is needed to decode the custom error name and parameters. 188 | 189 | > 💡 It's much more convenient to supply the ABIs and Interface objects for all smart contracts your application may interact with when creating the `ErrorDecoder` instance. You will then only need a single `ErrorDecoder` instance that you can reuse across your codebase to handle any smart contract errors. 190 | 191 | If you're expecting custom errors from multiple contracts or from external contracts called within your contract, you can provide the ABIs or interfaces of those contracts: 192 | 193 | ```typescript 194 | const myContractAbi = [...] 195 | const externalContractAbi = [...] 196 | 197 | // From here on, the errorDecoder is aware of all the custom errors throw from these contracts. 198 | const errorDecoder = ErrorDecoder.create([myContractAbi, externalContractAbi]) 199 | 200 | try {...} catch (err) { 201 | // It's aware of errors from MyContract, ExternalContract and ExternalContract errors emitted from MyContract. 202 | const decodedError = await errorDecoder.decode(err) 203 | // ... 204 | } 205 | ``` 206 | 207 | If you are using TypeChain in your project, it may be more convenient to pass the contract `Interface` objects directly: 208 | 209 | ```typescript 210 | // If you have the contract instances, you can access their `interface` property 211 | const errorDecoder = ErrorDecoder.create([MyContract.interface, MySecondContract.interface]) 212 | 213 | // Otherwise, you can use the `createInterface` method from the contract factory 214 | const errorDecoder = ErrorDecoder.create([ 215 | MyContract__factory.createInterface(), 216 | MySecondContract__factory.createInterface(), 217 | ]) 218 | ``` 219 | 220 | You can also mix both ABIs and contract `Interface` objects, and the library will sort out the ABIs for you. This can be useful if you just want to append adhoc ABI of external contracts so that their errors can be recognised when decoding: 221 | 222 | ```typescript 223 | const externalContractFullAbi = [...] 224 | const anotherExternalContractErrorOnlyAbi = [{ 225 | name: 'ExternalContractCustomError1', 226 | type: 'error', 227 | }] 228 | 229 | const errorDecoder = ErrorDecoder.create([MyContract__factory.createInterface(), externalContractFullAbi, anotherExternalContractErrorOnlyAbi]) 230 | ``` 231 | 232 | If the ABI of a custom error is not provided, the error name will be the selector of the custom error. In that case, you can check the selector of the error name in your reason mapper to handle the error accordingly: 233 | 234 | ```typescript 235 | const customReasonMapper = ({ name, args, reason }: DecodedError): string => { 236 | switch (name) { 237 | // For custom errors with ABI, you can check the error name directly 238 | case 'InvalidSwapToken': 239 | return `Invalid swap with token contract address ${args[0]}.` 240 | 241 | // For custom errors without ABI, you'll have to check the error name against the selector 242 | // Note that when ABI is not provided, the `args` will always be empty even if the custom error has parameters. 243 | case '0xec7240f7': 244 | return 'This is a custom error caught without its ABI provided.' 245 | 246 | default: 247 | return reason ?? 'An error has occurred' 248 | } 249 | } 250 | ``` 251 | 252 | ## Contributing 253 | 254 | Feel free to open an issue or PR for any bugs/improvements. 255 | -------------------------------------------------------------------------------- /contracts/MockContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.23; 3 | 4 | import "./MockNestedContract.sol"; 5 | 6 | contract MockContract { 7 | error CustomErrorNoParam(); 8 | error CustomErrorWithParams(address param1, uint256 param2); 9 | 10 | uint256 public value; 11 | 12 | function revertWithReason(string memory message) public { 13 | value++; 14 | revert(message); 15 | } 16 | 17 | function revertWithoutReason() public { 18 | value++; 19 | revert(); 20 | } 21 | 22 | function panicUnderflow() public { 23 | value++; 24 | uint8 num = 0; 25 | num--; 26 | } 27 | 28 | function revertWithCustomErrorNoParam() public { 29 | value++; 30 | revert CustomErrorNoParam(); 31 | } 32 | 33 | function revertWithCustomErrorWithParams(address param1, uint256 param2) public { 34 | value++; 35 | revert CustomErrorWithParams(param1, param2); 36 | } 37 | 38 | function revertWithCustomNestedError(address target, uint256 param) public { 39 | value++; 40 | MockNestedContract(target).revertNestedError(param); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /contracts/MockNestedContract.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity ^0.8.23; 3 | 4 | contract MockNestedContract { 5 | error NestedError(uint256 param); 6 | 7 | function revertNestedError(uint256 param) pure public { 8 | revert NestedError(param); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /hardhat.config.ts: -------------------------------------------------------------------------------- 1 | import { HardhatUserConfig } from "hardhat/config"; 2 | import "@nomicfoundation/hardhat-toolbox"; 3 | 4 | const config: HardhatUserConfig = { 5 | solidity: "0.8.23", 6 | }; 7 | 8 | export default config; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ethers-decode-error", 3 | "description": "Decode ethers.js smart contract errors into human-readable messages", 4 | "version": "2.0.0", 5 | "author": { 6 | "name": "superical", 7 | "url": "https://github.com/superical" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/superical/ethers-decode-error.git" 12 | }, 13 | "license": "Apache-2.0", 14 | "files": [ 15 | "dist" 16 | ], 17 | "type": "commonjs", 18 | "source": "src/index.ts", 19 | "exports": { 20 | "require": "./dist/index.js", 21 | "types": "./dist/index.d.ts", 22 | "default": "./dist/index.mjs" 23 | }, 24 | "types": "dist/index.d.ts", 25 | "main": "dist/index.js", 26 | "module": "dist/index.mjs", 27 | "umd:main": "dist/index.umd.js", 28 | "engines": { 29 | "node": ">=16" 30 | }, 31 | "peerDependencies": { 32 | "ethers": "^6.0.0" 33 | }, 34 | "devDependencies": { 35 | "@nomicfoundation/hardhat-toolbox": "^4.0.0", 36 | "@types/chai": "^4.3.11", 37 | "@types/mocha": "^10.0.6", 38 | "@types/node": "^18.19.8", 39 | "@types/sinon": "^17.0.3", 40 | "@typescript-eslint/eslint-plugin": "~5.59", 41 | "@typescript-eslint/parser": "~5.59", 42 | "chai": "^4.4.1", 43 | "eslint": "~8.38", 44 | "eslint-config-prettier": "~8.8", 45 | "ethers": "^6.10.0", 46 | "hardhat": "^2.19.4", 47 | "microbundle": "^0.15.1", 48 | "prettier": "~2.8", 49 | "rimraf": "~5.0", 50 | "semantic-release": "^23.0.0", 51 | "sinon": "^17.0.1", 52 | "ts-api-utils": "~0.0.44", 53 | "ts-node": "^10.9.2", 54 | "typescript": "~5.0" 55 | }, 56 | "scripts": { 57 | "start": "node build/src/main.js", 58 | "clean": "rimraf dist", 59 | "prebuild": "npm run lint", 60 | "build": "npm run clean && microbundle src/*.ts --tsconfig tsconfig.release.json", 61 | "build:watch": "tsc -w -p tsconfig.json", 62 | "lint": "eslint . --ext .ts --ext .mts", 63 | "test": "hardhat test", 64 | "prettier": "prettier --config .prettierrc --write .", 65 | "semantic-release:dry-run": "semantic-release --dry-run --no-ci --plugins @semantic-release/commit-analyzer,@semantic-release/release-notes-generator" 66 | }, 67 | "keywords": [ 68 | "blockchain", 69 | "ethers", 70 | "ethereum", 71 | "smart-contracts", 72 | "solidity", 73 | "typescript", 74 | "typechain", 75 | "errors", 76 | "decode-error", 77 | "ethers-decode-error", 78 | "ethers.js", 79 | "ethersjs", 80 | "rpc-error", 81 | "json-rpc" 82 | ] 83 | } 84 | -------------------------------------------------------------------------------- /src/common/constants.ts: -------------------------------------------------------------------------------- 1 | // Error(string) 2 | export const ERROR_STRING_PREFIX = '0x08c379a0' 3 | 4 | // Panic(uint256) 5 | export const PANIC_CODE_PREFIX = '0x4e487b71' 6 | -------------------------------------------------------------------------------- /src/common/enums.ts: -------------------------------------------------------------------------------- 1 | export enum ErrorType { 2 | EmptyError = 'EmptyError', 3 | RevertError = 'RevertError', 4 | PanicError = 'PanicError', 5 | CustomError = 'CustomError', 6 | UserRejectError = 'UserRejectError', 7 | RpcError = 'RpcError', 8 | UnknownError = 'UnknownError', 9 | } 10 | -------------------------------------------------------------------------------- /src/error-decoder.ts: -------------------------------------------------------------------------------- 1 | import { ErrorFragment, Fragment, Interface, JsonFragment, TransactionReceipt } from 'ethers' 2 | import { DecodedError } from './types' 3 | import { 4 | CustomErrorHandler, 5 | EmptyErrorHandler, 6 | ErrorHandler, 7 | PanicErrorHandler, 8 | RevertErrorHandler, 9 | RpcErrorHandler, 10 | UserRejectionHandler, 11 | } from './errors/handlers' 12 | import { unknownErrorResult } from './errors/results' 13 | 14 | export class ErrorDecoder { 15 | private readonly errorHandlers: ErrorHandler[] = [] 16 | 17 | private constructor( 18 | handlers: ErrorHandler[], 19 | public readonly errorInterface: Interface | undefined, 20 | ) { 21 | this.errorHandlers = handlers.map((handler) => ({ 22 | predicate: handler.predicate, 23 | handle: handler.handle, 24 | })) 25 | } 26 | 27 | private async getContractOrTransactionError(error: Error): Promise { 28 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 29 | const errorReceipt = (error as any).receipt as TransactionReceipt 30 | 31 | if (!errorReceipt) return error 32 | 33 | const resError = await this.getTransactionError(errorReceipt) 34 | 35 | if (!resError) return error 36 | 37 | return resError 38 | } 39 | 40 | private async getTransactionError(errorReceipt: TransactionReceipt): Promise { 41 | if (!errorReceipt || errorReceipt.status !== 0) { 42 | return undefined 43 | } 44 | const txHash = errorReceipt.hash 45 | const provider = errorReceipt.provider 46 | const tx = await provider.getTransaction(txHash) 47 | try { 48 | await provider.call({ 49 | ...tx, 50 | maxFeePerGas: undefined, 51 | maxPriorityFeePerGas: undefined, 52 | }) 53 | return null 54 | } catch (e) { 55 | return e as Error 56 | } 57 | } 58 | 59 | private getDataFromError(error: Error): string | undefined { 60 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 61 | const errorData = (error as any).data ?? (error as any).error?.data 62 | 63 | if (errorData === undefined) { 64 | return undefined 65 | } 66 | 67 | let returnData = typeof errorData === 'string' ? errorData : errorData.data 68 | 69 | if (typeof returnData === 'object' && returnData.data) { 70 | returnData = returnData.data 71 | } 72 | 73 | if (returnData === undefined || typeof returnData !== 'string') { 74 | return undefined 75 | } 76 | 77 | return returnData 78 | } 79 | 80 | public async decode(error: unknown | Error): Promise { 81 | if (!(error instanceof Error)) { 82 | return unknownErrorResult({ 83 | data: undefined, 84 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 85 | reason: (error as any).message ?? 'Invalid error', 86 | }) 87 | } 88 | 89 | const targetError = await this.getContractOrTransactionError(error) 90 | const returnData = this.getDataFromError(targetError) 91 | 92 | for (const { predicate, handle } of this.errorHandlers) { 93 | if (predicate(returnData, targetError)) { 94 | return handle(returnData, { errorInterface: this.errorInterface, error: targetError }) 95 | } 96 | } 97 | 98 | return unknownErrorResult({ 99 | data: returnData, 100 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 101 | reason: (targetError as any)?.message ?? 'Unexpected error', 102 | name: targetError?.name, 103 | }) 104 | } 105 | 106 | public static create( 107 | errorInterfaces?: ReadonlyArray, 108 | opts: { 109 | additionalErrorHandlers?: ErrorHandler[] 110 | } = {}, 111 | ): ErrorDecoder { 112 | const { additionalErrorHandlers } = opts 113 | let errorInterface: Interface | undefined 114 | if (errorInterfaces) { 115 | const errorFragments = errorInterfaces.flatMap((iface) => { 116 | if (iface instanceof Interface) { 117 | return iface.fragments.filter((fragment) => ErrorFragment.isFragment(fragment)) 118 | } else { 119 | return (iface as Fragment[]).filter( 120 | (fragment) => fragment.type === 'error' || ErrorFragment.isFragment(fragment), 121 | ) 122 | } 123 | }) 124 | errorInterface = new Interface(errorFragments) 125 | } 126 | const handlers = [ 127 | new EmptyErrorHandler(), 128 | new RevertErrorHandler(), 129 | new PanicErrorHandler(), 130 | new CustomErrorHandler(), 131 | new UserRejectionHandler(), 132 | new RpcErrorHandler(), 133 | ...(additionalErrorHandlers ?? []), 134 | ] 135 | return new ErrorDecoder(handlers, errorInterface) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/errors/handlers.ts: -------------------------------------------------------------------------------- 1 | import { AbiCoder, ErrorFragment, Interface } from 'ethers' 2 | import { panicErrorCodeToReason } from './panic' 3 | import { DecodedError } from '../types' 4 | import { ERROR_STRING_PREFIX, PANIC_CODE_PREFIX } from '../common/constants' 5 | import { 6 | customErrorResult, 7 | emptyErrorResult, 8 | panicErrorResult, 9 | revertErrorResult, 10 | rpcErrorResult, 11 | unknownErrorResult, 12 | userRejectErrorResult, 13 | } from './results' 14 | 15 | type ErrorHandlerErrorInfo = { errorInterface: Interface; error: Error } 16 | 17 | export interface ErrorHandler { 18 | predicate: (data: string | undefined, error: Error) => boolean 19 | handle: (data: string | undefined, errorInfo: ErrorHandlerErrorInfo) => DecodedError 20 | } 21 | 22 | export class EmptyErrorHandler implements ErrorHandler { 23 | public predicate(data: string): boolean { 24 | return data === '0x' 25 | } 26 | 27 | public handle(data: string): DecodedError { 28 | return emptyErrorResult({ data }) 29 | } 30 | } 31 | 32 | export class RevertErrorHandler implements ErrorHandler { 33 | public predicate(data: string): boolean { 34 | return data?.startsWith(ERROR_STRING_PREFIX) 35 | } 36 | 37 | public handle(data: string): DecodedError { 38 | const encodedReason = data.slice(ERROR_STRING_PREFIX.length) 39 | const abi = new AbiCoder() 40 | try { 41 | const fragment = ErrorFragment.from('Error(string)') 42 | const args = abi.decode(fragment.inputs, `0x${encodedReason}`) 43 | const reason = args[0] as string 44 | return revertErrorResult({ data, fragment, reason, args }) 45 | } catch (e) { 46 | return unknownErrorResult({ reason: 'Unknown error returned', data }) 47 | } 48 | } 49 | } 50 | 51 | export class PanicErrorHandler implements ErrorHandler { 52 | public predicate(data: string): boolean { 53 | return data?.startsWith(PANIC_CODE_PREFIX) 54 | } 55 | 56 | public handle(data: string): DecodedError { 57 | const encodedReason = data.slice(PANIC_CODE_PREFIX.length) 58 | const abi = new AbiCoder() 59 | try { 60 | const fragment = ErrorFragment.from('Panic(uint256)') 61 | const args = abi.decode(fragment.inputs, `0x${encodedReason}`) 62 | const reason = panicErrorCodeToReason(args[0] as bigint) ?? 'Unknown panic code' 63 | return panicErrorResult({ data, fragment, reason, args }) 64 | } catch (e) { 65 | return unknownErrorResult({ reason: 'Unknown panic error', data }) 66 | } 67 | } 68 | } 69 | 70 | export class CustomErrorHandler implements ErrorHandler { 71 | public predicate(data: string): boolean { 72 | return ( 73 | data && 74 | data !== '0x' && 75 | !data?.startsWith(ERROR_STRING_PREFIX) && 76 | !data?.startsWith(PANIC_CODE_PREFIX) 77 | ) 78 | } 79 | 80 | public handle(data: string, { errorInterface }: ErrorHandlerErrorInfo): DecodedError { 81 | let result: Parameters[0] = { data } 82 | if (errorInterface) { 83 | const customError = errorInterface.parseError(data) 84 | 85 | if (customError) { 86 | const { fragment, args, name: reason } = customError 87 | result = { ...result, fragment, reason, args } 88 | } 89 | } 90 | 91 | return customErrorResult(result) 92 | } 93 | } 94 | 95 | export class UserRejectionHandler implements ErrorHandler { 96 | public predicate(data: string, error: Error): boolean { 97 | return !data && error?.message?.includes('rejected transaction') 98 | } 99 | 100 | public handle(_data: string, { error }: ErrorHandlerErrorInfo): DecodedError { 101 | return userRejectErrorResult({ 102 | data: null, 103 | reason: error.message ?? 'The transaction was rejected', 104 | }) 105 | } 106 | } 107 | 108 | export class RpcErrorHandler implements ErrorHandler { 109 | public predicate(data: string, error: Error): boolean { 110 | return ( 111 | !data && 112 | error.message && 113 | !error?.message?.includes('rejected transaction') && 114 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 115 | (error as any).code !== undefined 116 | ) 117 | } 118 | 119 | public handle(_data: string, { error }: ErrorHandlerErrorInfo): DecodedError { 120 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 121 | const rpcError = error as any 122 | const reason = rpcError.info?.error?.message ?? rpcError.shortMessage ?? rpcError.message 123 | return rpcErrorResult({ data: null, name: rpcError.code, reason }) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/errors/panic.ts: -------------------------------------------------------------------------------- 1 | // From Hardhat's panic codes 2 | // https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require 3 | export const panicErrorCodeToReason = (errorCode: bigint): string | undefined => { 4 | switch (errorCode) { 5 | case 0x0n: 6 | return 'Generic compiler inserted panic' 7 | case 0x1n: 8 | return 'Assertion error' 9 | case 0x11n: 10 | return 'Arithmetic operation underflowed or overflowed outside of an unchecked block' 11 | case 0x12n: 12 | return 'Division or modulo division by zero' 13 | case 0x21n: 14 | return 'Tried to convert a value into an enum, but the value was too big or negative' 15 | case 0x22n: 16 | return 'Incorrectly encoded storage byte array' 17 | case 0x31n: 18 | return '.pop() was called on an empty array' 19 | case 0x32n: 20 | return 'Array accessed at an out-of-bounds or negative index' 21 | case 0x41n: 22 | return 'Too much memory was allocated, or an array was created that is too large' 23 | case 0x51n: 24 | return 'Called a zero-initialized variable of internal function type' 25 | } 26 | return undefined 27 | } 28 | -------------------------------------------------------------------------------- /src/errors/results.ts: -------------------------------------------------------------------------------- 1 | import { ErrorDescription, ErrorFragment, Result } from 'ethers' 2 | import { DecodedError } from '../types' 3 | import { ErrorType } from '../common/enums' 4 | 5 | type ErrorResultFormatterParam = { 6 | data: string 7 | reason?: string 8 | args?: Result 9 | fragment?: ErrorFragment 10 | selector?: string 11 | name?: string 12 | } 13 | 14 | type ErrorResultFormatter = (params: ErrorResultFormatterParam) => DecodedError 15 | 16 | const formatReason = ( 17 | reason: string | undefined | null, 18 | defaultReason: string | null, 19 | ): string | null => (reason && reason.trim() !== '' ? reason : defaultReason) 20 | 21 | const baseErrorResult: ( 22 | params: ErrorResultFormatterParam & { type: ErrorType }, 23 | ) => DecodedError = ({ type, data, reason, fragment, args, selector, name }) => { 24 | let res: DecodedError = { 25 | type, 26 | reason: formatReason(reason, null), 27 | data: data ?? null, 28 | fragment: null, 29 | args: args ?? new Result(), 30 | selector: selector ?? null, 31 | name: name ?? null, 32 | signature: null, 33 | } 34 | if (fragment) { 35 | const desc = new ErrorDescription(fragment, fragment.selector, args) 36 | res = { 37 | ...res, 38 | ...desc, 39 | } 40 | } 41 | return res 42 | } 43 | 44 | export const emptyErrorResult: ErrorResultFormatter = ({ data }) => 45 | baseErrorResult({ 46 | type: ErrorType.EmptyError, 47 | data, 48 | }) 49 | 50 | export const userRejectErrorResult: ErrorResultFormatter = ({ data = null, reason }) => 51 | baseErrorResult({ 52 | type: ErrorType.UserRejectError, 53 | reason: formatReason(reason, 'User has rejected the transaction'), 54 | data, 55 | }) 56 | 57 | export const revertErrorResult: ErrorResultFormatter = ({ data, reason, fragment, args }) => { 58 | return baseErrorResult({ 59 | type: ErrorType.RevertError, 60 | reason, 61 | data, 62 | fragment, 63 | args, 64 | }) 65 | } 66 | 67 | export const unknownErrorResult: ErrorResultFormatter = ({ data, reason, name }) => { 68 | return baseErrorResult({ 69 | type: ErrorType.UnknownError, 70 | reason: formatReason(reason, 'Unknown error'), 71 | data, 72 | name 73 | }) 74 | } 75 | 76 | export const panicErrorResult: ErrorResultFormatter = ({ data, reason, args }) => 77 | baseErrorResult({ 78 | type: ErrorType.PanicError, 79 | reason, 80 | data, 81 | args, 82 | }) 83 | 84 | export const customErrorResult: ErrorResultFormatter = ({ data, reason, fragment, args }) => { 85 | const selector = data.slice(0, 10) 86 | return baseErrorResult({ 87 | type: ErrorType.CustomError, 88 | reason: formatReason(reason, `No ABI for custom error ${selector}`), 89 | data, 90 | fragment, 91 | args, 92 | selector, 93 | name: selector, 94 | }) 95 | } 96 | 97 | export const rpcErrorResult: ErrorResultFormatter = ({ reason, name }) => 98 | baseErrorResult({ 99 | type: ErrorType.RpcError, 100 | reason: formatReason(reason, 'Error from JSON RPC provider'), 101 | data: null, 102 | name: name?.toString() ?? null, 103 | }) 104 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type * from './types' 2 | 3 | export * from './common/enums' 4 | export { ErrorDecoder } from './error-decoder' 5 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { ErrorType } from './common/enums' 2 | import { ErrorDescription } from "ethers"; 3 | 4 | export type DecodedError = ErrorDescription & { 5 | type: ErrorType 6 | reason: string | null 7 | data: string | null 8 | } 9 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import { ethers } from 'hardhat' 2 | import { expect } from 'chai' 3 | import sinon from 'sinon' 4 | import type { SinonSpy } from 'sinon' 5 | import { getBytes, hexlify, concat, zeroPadValue } from 'ethers' 6 | import type { ContractFactory } from 'ethers' 7 | import { 8 | MockContract, 9 | MockContract__factory, 10 | MockNestedContract, 11 | MockNestedContract__factory, 12 | } from '../typechain-types' 13 | import { ErrorDecoder } from '../src' 14 | import { DecodedError, ErrorType } from '../src' 15 | 16 | describe('ErrorDecoder', () => { 17 | let contract: MockContract 18 | 19 | let errorDecoder: ErrorDecoder 20 | let decodedError: DecodedError 21 | 22 | beforeEach(async () => { 23 | const contractFactory = (await ethers.getContractFactory( 24 | 'MockContract', 25 | )) as ContractFactory as MockContract__factory 26 | contract = await contractFactory.deploy() 27 | 28 | errorDecoder = ErrorDecoder.create() 29 | }) 30 | 31 | describe('When reverted with an unknown error', () => { 32 | const fakeUnknownError = {} 33 | 34 | beforeEach(async () => { 35 | decodedError = await errorDecoder.decode(fakeUnknownError) 36 | }) 37 | 38 | it('should return error type as UnknownError', async () => { 39 | expect(decodedError.type).to.equal(ErrorType.UnknownError) 40 | }) 41 | 42 | it('should use error message if it exists', async () => { 43 | const fakeErrorMsg = 'Test message' 44 | decodedError = await errorDecoder.decode({ message: fakeErrorMsg }) 45 | 46 | expect(decodedError.reason).to.equal(fakeErrorMsg) 47 | }) 48 | 49 | it('should return error message as Invalid error', async () => { 50 | expect(decodedError.reason).to.equal('Invalid error') 51 | }) 52 | 53 | it('should return null data', async () => { 54 | expect(decodedError.data).to.be.null 55 | }) 56 | }) 57 | 58 | describe('When reverted error has no data', () => { 59 | describe('When reverted due to user rejection', () => { 60 | const fakeUnknownError = new Error('The user rejected transaction in wallet') 61 | 62 | beforeEach(async () => { 63 | decodedError = await errorDecoder.decode(fakeUnknownError) 64 | }) 65 | 66 | it('should return error type as UserError', async () => { 67 | expect(decodedError.type).to.equal(ErrorType.UserRejectError) 68 | }) 69 | 70 | it('should return user rejected error message', async () => { 71 | expect(decodedError.reason).to.equal(fakeUnknownError.message) 72 | }) 73 | 74 | it('should return null data', async () => { 75 | expect(decodedError.data).to.be.null 76 | }) 77 | }) 78 | 79 | describe('When reverted due to other reasons', () => { 80 | const fakeErrorMessage = 'Some other reasons' 81 | const fakeUnknownError = new Error(fakeErrorMessage) 82 | 83 | beforeEach(async () => { 84 | decodedError = await errorDecoder.decode(fakeUnknownError) 85 | }) 86 | 87 | it('should return error type as UnknownError', async () => { 88 | expect(decodedError.type).to.equal(ErrorType.UnknownError) 89 | }) 90 | 91 | it('should return the error message', async () => { 92 | expect(decodedError.reason).to.equal(fakeErrorMessage) 93 | }) 94 | 95 | it('should return null data', async () => { 96 | expect(decodedError.data).to.be.null 97 | }) 98 | }) 99 | 100 | describe('When reverted without known reason', () => { 101 | const fakeUnknownError = new Error() 102 | 103 | beforeEach(async () => { 104 | decodedError = await errorDecoder.decode(fakeUnknownError) 105 | }) 106 | 107 | it('should return error type as UnknownError', async () => { 108 | expect(decodedError.type).to.equal(ErrorType.UnknownError) 109 | }) 110 | 111 | it('should return the error message as Unknown error', async () => { 112 | expect(decodedError.reason).to.equal('Unknown error') 113 | }) 114 | 115 | it('should return null data', async () => { 116 | expect(decodedError.data).to.be.null 117 | }) 118 | }) 119 | }) 120 | 121 | describe('When reverted with normal revert', () => { 122 | describe('When reverted with reason', () => { 123 | beforeEach(async () => { 124 | try { 125 | await contract.revertWithReason('Test message') 126 | expect.fail('Expected to revert') 127 | } catch (e) { 128 | decodedError = await errorDecoder.decode(e) 129 | } 130 | }) 131 | 132 | it('should return error type as RevertError', async () => { 133 | expect(decodedError.type).to.equal(ErrorType.RevertError) 134 | }) 135 | 136 | it('should return args with reason', async () => { 137 | expect(decodedError.args[0]).to.equal('Test message') 138 | }) 139 | 140 | it('should return revert error data', async () => { 141 | const errorData = 142 | '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c54657374206d6573736167650000000000000000000000000000000000000000' 143 | 144 | expect(decodedError.data).to.equal(errorData) 145 | }) 146 | 147 | it('should capture the revert', async () => { 148 | expect(decodedError.reason).to.equal('Test message') 149 | }) 150 | }) 151 | 152 | describe('When reverted without reason', () => { 153 | beforeEach(async () => { 154 | try { 155 | await contract.revertWithoutReason() 156 | expect.fail('Expected to revert') 157 | } catch (e) { 158 | decodedError = await errorDecoder.decode(e) 159 | } 160 | }) 161 | 162 | it('should return error type as EmptyError', async () => { 163 | expect(decodedError.type).to.equal(ErrorType.EmptyError) 164 | }) 165 | 166 | it('should return empty args', async () => { 167 | expect(decodedError.args.length).to.equal(0) 168 | }) 169 | 170 | it('should return revert error data', async () => { 171 | const errorData = '0x' 172 | 173 | expect(decodedError.data).to.equal(errorData) 174 | }) 175 | 176 | it('should capture revert without reasons', async () => { 177 | expect(decodedError.reason).to.be.null 178 | }) 179 | }) 180 | }) 181 | 182 | describe('When reverted with panic error', () => { 183 | beforeEach(async () => { 184 | try { 185 | await contract.panicUnderflow() 186 | expect.fail('Expected to revert') 187 | } catch (e) { 188 | decodedError = await errorDecoder.decode(e) 189 | } 190 | }) 191 | 192 | it('should return error type as PanicError', async () => { 193 | expect(decodedError.type).to.equal(ErrorType.PanicError) 194 | }) 195 | 196 | it('should return args containing panic 0x11n', async () => { 197 | expect(decodedError.args[0]).to.equal(0x11n) 198 | }) 199 | 200 | it('should return panic error data', async () => { 201 | const errorData = concat(['0x4e487b71', zeroPadValue(getBytes('0x11'), 32)]) 202 | 203 | expect(decodedError.data).to.equal(errorData) 204 | }) 205 | 206 | it('should capture the panic error', async () => { 207 | expect(decodedError.reason).to.equal( 208 | 'Arithmetic operation underflowed or overflowed outside of an unchecked block', 209 | ) 210 | }) 211 | }) 212 | 213 | describe('When reverted with custom error', () => { 214 | const ifaceCustomErrorNoParam = '0xec7240f7' 215 | const ifaceCustomErrorWithParams = '0x74649f48' 216 | 217 | const fakeAddress = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' 218 | const fakeUint = '12345' 219 | 220 | const abi = [ 221 | { 222 | name: 'CustomErrorNoParam', // 0xec7240f7 223 | type: 'error', 224 | }, 225 | { 226 | inputs: [ 227 | { 228 | internalType: 'address', 229 | name: 'param1', 230 | type: 'address', 231 | }, 232 | { 233 | internalType: 'uint256', 234 | name: 'param2', 235 | type: 'uint256', 236 | }, 237 | ], 238 | name: 'CustomErrorWithParams', // 0x74649f48 239 | type: 'error', 240 | }, 241 | ] 242 | 243 | const testMatrixUseAbiArray = [true, false] 244 | Object.keys(testMatrixUseAbiArray).forEach((useAbiArray) => { 245 | beforeEach(async () => { 246 | errorDecoder = ErrorDecoder.create( 247 | useAbiArray ? [abi] : [MockContract__factory.createInterface()], 248 | ) 249 | }) 250 | 251 | describe(`When using ${useAbiArray ? 'ABI array' : 'contract interface'}`, () => { 252 | describe('When custom error has no parameters', () => { 253 | const errorData = ifaceCustomErrorNoParam 254 | 255 | beforeEach(async () => { 256 | try { 257 | await contract.revertWithCustomErrorNoParam() 258 | expect.fail('Expected to revert') 259 | } catch (e) { 260 | decodedError = await errorDecoder.decode(e) 261 | } 262 | }) 263 | 264 | it('should capture custom errors with no parameters', async () => { 265 | expect(decodedError.reason).to.equal('CustomErrorNoParam') 266 | }) 267 | 268 | it('should return custom error data', async () => { 269 | expect(decodedError.data).to.equal(errorData) 270 | }) 271 | 272 | it('should return empty args', async () => { 273 | expect(decodedError.args.length).to.equal(0) 274 | }) 275 | 276 | it('should return error type as CustomError', async () => { 277 | expect(decodedError.type).to.equal(ErrorType.CustomError) 278 | }) 279 | 280 | describe('When reverted custom error is not in ABI', () => { 281 | beforeEach(async () => { 282 | errorDecoder = ErrorDecoder.create([[abi[1]]]) 283 | try { 284 | await contract.revertWithCustomErrorNoParam() 285 | expect.fail('Expected to revert') 286 | } catch (e) { 287 | decodedError = await errorDecoder.decode(e) 288 | } 289 | }) 290 | 291 | it('should return empty args', async () => { 292 | expect(decodedError.args.length).to.equal(0) 293 | }) 294 | 295 | it('should return the selector of custom error name as reason', async () => { 296 | expect(decodedError.reason).to.equal( 297 | `No ABI for custom error ${ifaceCustomErrorNoParam}`, 298 | ) 299 | }) 300 | 301 | it('should return the selector of custom error as name', async () => { 302 | expect(decodedError.name).to.equal(ifaceCustomErrorNoParam) 303 | }) 304 | 305 | it('should return custom error data', async () => { 306 | expect(decodedError.data).to.equal(errorData) 307 | }) 308 | 309 | it('should return error type as CustomError', async () => { 310 | expect(decodedError.type).to.equal(ErrorType.CustomError) 311 | }) 312 | }) 313 | 314 | describe('When no ABI is supplied for custom error', () => { 315 | beforeEach(async () => { 316 | errorDecoder = ErrorDecoder.create() 317 | try { 318 | await contract.revertWithCustomErrorNoParam() 319 | expect.fail('Expected to revert') 320 | } catch (e) { 321 | decodedError = await errorDecoder.decode(e) 322 | } 323 | }) 324 | 325 | it('should return the selector of custom error name as reason', async () => { 326 | expect(decodedError.reason).to.equal( 327 | `No ABI for custom error ${ifaceCustomErrorNoParam}`, 328 | ) 329 | }) 330 | 331 | it('should return the selector of custom error as name', async () => { 332 | expect(decodedError.name).to.equal(ifaceCustomErrorNoParam) 333 | }) 334 | 335 | it('should return empty args', async () => { 336 | expect(decodedError.args.length).to.equal(0) 337 | }) 338 | 339 | it('should return custom error data', async () => { 340 | expect(decodedError.data).to.equal(errorData) 341 | }) 342 | 343 | it('should return error type as CustomError', async () => { 344 | expect(decodedError.type).to.equal(ErrorType.CustomError) 345 | }) 346 | }) 347 | }) 348 | 349 | describe('When custom error has parameters', () => { 350 | const errorData = concat([ 351 | ifaceCustomErrorWithParams, 352 | zeroPadValue(getBytes(fakeAddress), 32), 353 | zeroPadValue(hexlify(`0x${BigInt(fakeUint).toString(16)}`), 32), 354 | ]) 355 | 356 | beforeEach(async () => { 357 | try { 358 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 359 | expect.fail('Expected to revert') 360 | } catch (e) { 361 | decodedError = await errorDecoder.decode(e) 362 | } 363 | }) 364 | 365 | it('should capture custom errors with parameters', async () => { 366 | expect(decodedError.reason).to.equal('CustomErrorWithParams') 367 | }) 368 | 369 | it('should return custom error data', async () => { 370 | expect(decodedError.data).to.equal(errorData) 371 | }) 372 | 373 | it('should return custom error parameters in args', async () => { 374 | expect(decodedError.args[0]).to.equal(fakeAddress) 375 | expect(decodedError.args[1]).to.equal(fakeUint) 376 | 377 | expect(decodedError.args['param1']).to.equal(fakeAddress) 378 | expect(decodedError.args['param2']).to.equal(fakeUint) 379 | }) 380 | 381 | it('should return error type as CustomError', async () => { 382 | expect(decodedError.type).to.equal(ErrorType.CustomError) 383 | }) 384 | 385 | describe('When reverted custom error is not in ABI', () => { 386 | beforeEach(async () => { 387 | errorDecoder = ErrorDecoder.create([[abi[0]]]) 388 | try { 389 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 390 | expect.fail('Expected to revert') 391 | } catch (e) { 392 | decodedError = await errorDecoder.decode(e) 393 | } 394 | }) 395 | 396 | it('should return empty args', async () => { 397 | expect(decodedError.args.length).to.equal(0) 398 | }) 399 | 400 | it('should return the selector of custom error name as reason', async () => { 401 | expect(decodedError.reason).to.equal( 402 | `No ABI for custom error ${ifaceCustomErrorWithParams}`, 403 | ) 404 | }) 405 | 406 | it('should return the selector of custom error as name', async () => { 407 | expect(decodedError.name).to.equal(ifaceCustomErrorWithParams) 408 | }) 409 | 410 | it('should return custom error data', async () => { 411 | expect(decodedError.data).to.equal(errorData) 412 | }) 413 | 414 | it('should return error type as CustomError', async () => { 415 | expect(decodedError.type).to.equal(ErrorType.CustomError) 416 | }) 417 | }) 418 | 419 | describe('When no ABI is supplied for custom error', () => { 420 | beforeEach(async () => { 421 | errorDecoder = ErrorDecoder.create() 422 | try { 423 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 424 | expect.fail('Expected to revert') 425 | } catch (e) { 426 | decodedError = await errorDecoder.decode(e) 427 | } 428 | }) 429 | 430 | it('should return the selector of custom error name as reason', async () => { 431 | expect(decodedError.reason).to.equal( 432 | `No ABI for custom error ${ifaceCustomErrorWithParams}`, 433 | ) 434 | }) 435 | 436 | it('should return the selector of custom error as name', async () => { 437 | expect(decodedError.name).to.equal(ifaceCustomErrorWithParams) 438 | }) 439 | 440 | it('should return empty args', async () => { 441 | expect(decodedError.args.length).to.equal(0) 442 | }) 443 | 444 | it('should return custom error data', async () => { 445 | expect(decodedError.data).to.equal(errorData) 446 | }) 447 | 448 | it('should return error type as CustomError', async () => { 449 | expect(decodedError.type).to.equal(ErrorType.CustomError) 450 | }) 451 | }) 452 | }) 453 | }) 454 | }) 455 | 456 | describe('When reverted with nested custom error', () => { 457 | let nestedContract: MockNestedContract 458 | let nestedContractAddress: string 459 | 460 | const nestedErrorAbi = [ 461 | { 462 | inputs: [ 463 | { 464 | internalType: 'uint256', 465 | name: 'param', 466 | type: 'uint256', 467 | }, 468 | ], 469 | name: 'NestedError', 470 | type: 'error', 471 | }, 472 | ] 473 | 474 | beforeEach(async () => { 475 | const nestedContractFactory = (await ethers.getContractFactory( 476 | 'MockNestedContract', 477 | )) as ContractFactory as MockNestedContract__factory 478 | nestedContract = await nestedContractFactory.deploy() 479 | nestedContractAddress = await nestedContract.getAddress() 480 | }) 481 | 482 | describe('When provided only with interface objects', () => { 483 | beforeEach(async () => { 484 | errorDecoder = ErrorDecoder.create([ 485 | MockContract__factory.createInterface(), 486 | MockNestedContract__factory.createInterface(), 487 | ]) 488 | }) 489 | 490 | it('should merge the interfaces the recognise error from MockContract', async () => { 491 | try { 492 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 493 | expect.fail('Expected to revert') 494 | } catch (e) { 495 | decodedError = await errorDecoder.decode(e) 496 | } 497 | 498 | expect(decodedError.name).to.equal('CustomErrorWithParams') 499 | }) 500 | 501 | it('should merge the interfaces the recognise error from MockNestedContract', async () => { 502 | try { 503 | await contract.revertWithCustomNestedError(nestedContractAddress, fakeUint) 504 | expect.fail('Expected to revert') 505 | } catch (e) { 506 | decodedError = await errorDecoder.decode(e) 507 | } 508 | 509 | expect(decodedError.name).to.equal('NestedError') 510 | }) 511 | }) 512 | 513 | describe('When provided only with ABIs', () => { 514 | beforeEach(async () => { 515 | errorDecoder = ErrorDecoder.create([abi, nestedErrorAbi]) 516 | }) 517 | 518 | it('should merge the interfaces the recognise error from MockContract', async () => { 519 | try { 520 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 521 | expect.fail('Expected to revert') 522 | } catch (e) { 523 | decodedError = await errorDecoder.decode(e) 524 | } 525 | 526 | expect(decodedError.name).to.equal('CustomErrorWithParams') 527 | }) 528 | 529 | it('should merge the interfaces the recognise error from MockNestedContract', async () => { 530 | try { 531 | await contract.revertWithCustomNestedError(nestedContractAddress, fakeUint) 532 | expect.fail('Expected to revert') 533 | } catch (e) { 534 | decodedError = await errorDecoder.decode(e) 535 | } 536 | 537 | expect(decodedError.name).to.equal('NestedError') 538 | }) 539 | }) 540 | 541 | describe('When provided interface objects and ABIs', () => { 542 | beforeEach(async () => { 543 | errorDecoder = ErrorDecoder.create([abi, MockNestedContract__factory.createInterface()]) 544 | }) 545 | 546 | it('should merge the interfaces the recognise error from MockContract', async () => { 547 | try { 548 | await contract.revertWithCustomErrorWithParams(fakeAddress, fakeUint) 549 | expect.fail('Expected to revert') 550 | } catch (e) { 551 | decodedError = await errorDecoder.decode(e) 552 | } 553 | 554 | expect(decodedError.name).to.equal('CustomErrorWithParams') 555 | }) 556 | 557 | it('should merge the interfaces the recognise error from MockNestedContract', async () => { 558 | try { 559 | await contract.revertWithCustomNestedError(nestedContractAddress, fakeUint) 560 | expect.fail('Expected to revert') 561 | } catch (e) { 562 | decodedError = await errorDecoder.decode(e) 563 | } 564 | 565 | expect(decodedError.name).to.equal('NestedError') 566 | }) 567 | }) 568 | }) 569 | }) 570 | 571 | describe('When reverted not due to contract errors', () => { 572 | describe('When decoding RPC errors', () => { 573 | beforeEach(async () => { 574 | try { 575 | await contract.revertWithReason('Test message', { 576 | gasLimit: 100000, 577 | gasPrice: '1180820112192848923743894728934', 578 | }) 579 | expect.fail('Expected to revert') 580 | } catch (e) { 581 | decodedError = await errorDecoder.decode(e) 582 | } 583 | }) 584 | 585 | it('should return error type as RpcError', async () => { 586 | expect(decodedError.type).to.equal(ErrorType.RpcError) 587 | }) 588 | 589 | it('should return error code as name', async () => { 590 | expect(decodedError.name).to.equal('-32000') 591 | }) 592 | 593 | it('should return the error reason', async () => { 594 | expect(decodedError.reason).to.contain("sender doesn't have enough funds to send tx") 595 | }) 596 | 597 | it('should return data as null', async () => { 598 | expect(decodedError.data).to.be.null 599 | }) 600 | 601 | it('should return empty args', async () => { 602 | expect(decodedError.args.length).to.equal(0) 603 | }) 604 | }) 605 | 606 | describe('When obtaining the error message in RPC errors', () => { 607 | const FakeRpcError = class extends Error { 608 | public constructor( 609 | public code?: string, 610 | public info?: { error: { code: number; message: string } }, 611 | public shortMessage?: string, 612 | ) { 613 | super('Fake error object message') 614 | } 615 | } 616 | 617 | let fakeRpcError = new FakeRpcError() 618 | 619 | beforeEach(async () => { 620 | fakeRpcError = new FakeRpcError( 621 | 'INSUFFICIENT_FUNDS', 622 | { 623 | error: { 624 | code: -32000, 625 | message: 'insufficient funds for gas * price + value: balance 0', 626 | }, 627 | }, 628 | 'insufficient funds for intrinsic transaction cost', 629 | ) 630 | }) 631 | 632 | it('should use long error message if exists', async () => { 633 | decodedError = await errorDecoder.decode(fakeRpcError) 634 | 635 | expect(decodedError.reason).to.equal(fakeRpcError.info.error.message) 636 | }) 637 | 638 | it('should use short message if long error message does not exist', async () => { 639 | fakeRpcError.info = undefined 640 | 641 | decodedError = await errorDecoder.decode(fakeRpcError) 642 | 643 | expect(decodedError.reason).to.equal(fakeRpcError.shortMessage) 644 | }) 645 | 646 | it('should fallback to using message in error object', async () => { 647 | fakeRpcError.info = undefined 648 | fakeRpcError.shortMessage = undefined 649 | 650 | decodedError = await errorDecoder.decode(fakeRpcError) 651 | 652 | expect(decodedError.reason).to.equal(fakeRpcError.message) 653 | }) 654 | }) 655 | }) 656 | 657 | describe('When transaction mined but reverted', () => { 658 | const FakeTxError = class extends Error { 659 | public receipt: { 660 | status: number 661 | provider: { 662 | getTransaction: SinonSpy 663 | call: SinonSpy 664 | } 665 | } 666 | public constructor(public status: number) { 667 | super('Fake transaction error') 668 | this.receipt = { 669 | status, 670 | provider: { 671 | getTransaction: sinon.fake(), 672 | call: sinon.spy(), 673 | }, 674 | } 675 | } 676 | } 677 | 678 | beforeEach(async () => { 679 | errorDecoder = ErrorDecoder.create() 680 | }) 681 | 682 | describe('When receipt status is zero', () => { 683 | const fakeTxError = new FakeTxError(0) 684 | 685 | beforeEach(async () => { 686 | decodedError = await errorDecoder.decode(fakeTxError) 687 | }) 688 | 689 | it('should call transaction for error data', async () => { 690 | expect(fakeTxError.receipt.provider.call.calledOnce).to.be.true 691 | }) 692 | 693 | it('should return name as error name', async () => { 694 | expect(decodedError.name).to.equal('Error') 695 | }) 696 | 697 | it('should return reason as error message', async () => { 698 | expect(decodedError.reason).to.equal('Fake transaction error') 699 | }) 700 | }) 701 | 702 | describe('When receipt status is non-zero', () => { 703 | const fakeTxError = new FakeTxError(1) 704 | 705 | it('should not call transaction for error data', async () => { 706 | await errorDecoder.decode(fakeTxError) 707 | 708 | expect(fakeTxError.receipt.provider.call.calledOnce).to.be.false 709 | }) 710 | }) 711 | }) 712 | }) 713 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2022", 4 | "module": "commonjs", 5 | "esModuleInterop": true, 6 | "lib": ["ES2022"], 7 | "moduleResolution": "Node", 8 | "baseUrl": ".", 9 | "outDir": "build", 10 | "allowSyntheticDefaultImports": true, 11 | "importHelpers": true, 12 | "alwaysStrict": true, 13 | "sourceMap": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "strict": true, 16 | "skipLibCheck": true, 17 | "resolveJsonModule": true, 18 | "noFallthroughCasesInSwitch": true, 19 | "noImplicitReturns": true, 20 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | "noImplicitAny": false, 23 | "noImplicitThis": false, 24 | "strictNullChecks": false 25 | }, 26 | "include": ["src/**/*", "test/**/*"], 27 | "exclude": ["node_modules", "dist"], 28 | "files": ["./hardhat.config.ts"] 29 | } 30 | -------------------------------------------------------------------------------- /tsconfig.release.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "sourceMap": false, 5 | "removeComments": true 6 | }, 7 | "include": ["src/**/*"], 8 | "files": [] 9 | } 10 | --------------------------------------------------------------------------------