├── .nvmrc ├── .npmrc ├── tsconfig.build.json ├── .prettierrc ├── .npmignore ├── src ├── index.ts ├── ethers.contract.ts ├── ethers.decorators.ts ├── ethers.module.ts ├── ethers.signer.ts ├── ethers.interface.ts ├── ethers.utils.ts ├── ethers-core.module.ts ├── ethers.providers.ts ├── ethers.constants.ts └── ethers.custom-rpcs.ts ├── test ├── utils │ ├── platforms.ts │ ├── extraWait.ts │ ├── appRequest.ts │ ├── ABI.json │ ├── constants.ts │ └── mockResponses.ts ├── ethers.utils.spec.ts ├── ethers.contract.spec.ts ├── ethers.custom-rpcs.spec.ts ├── ethers.signer.spec.ts └── ethers.decorators.spec.ts ├── tsconfig.json ├── CONTRIBUTING.md ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── ISSUE_TEMPLATE.md └── workflows │ └── codeql-analysis.yml ├── eslint.config.js ├── .circleci └── config.yml ├── package.json ├── .gitignore ├── CHANGELOG.md ├── LICENSE └── README.md /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/jod 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=true 2 | scripts-prepend-node-path=true 3 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"] 4 | } 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "singleQuote": true, 4 | "semi": false, 5 | "bracketSpacing": true, 6 | "trailingComma": "all" 7 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | __tests__/ 2 | .github/ 3 | .circleci/ 4 | coverage/ 5 | *.tsbuildinfo 6 | *.js.map 7 | src/ 8 | .eslintrc.js 9 | .gitignore 10 | .prettierrc 11 | .travis.yml 12 | nest-cli.json 13 | tsconfig.build.json 14 | tsconfig.json 15 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './ethers.constants' 2 | export * from './ethers.contract' 3 | export * from './ethers.custom-rpcs' 4 | export * from './ethers.decorators' 5 | export * from './ethers.interface' 6 | export * from './ethers.module' 7 | export * from './ethers.signer' 8 | export * from './ethers.utils' 9 | -------------------------------------------------------------------------------- /test/utils/platforms.ts: -------------------------------------------------------------------------------- 1 | import { Type } from '@nestjs/common' 2 | import { AbstractHttpAdapter } from '@nestjs/core' 3 | import { ExpressAdapter } from '@nestjs/platform-express' 4 | import { FastifyAdapter } from '@nestjs/platform-fastify' 5 | 6 | export type Adapter = Type> 7 | 8 | export const platforms: Adapter[] = [ExpressAdapter, FastifyAdapter] 9 | -------------------------------------------------------------------------------- /src/ethers.contract.ts: -------------------------------------------------------------------------------- 1 | import { VoidSigner, Wallet, Contract, InterfaceAbi, AbstractProvider } from 'ethers' 2 | 3 | export class EthersContract { 4 | private readonly provider: AbstractProvider 5 | 6 | constructor(provider: AbstractProvider) { 7 | this.provider = provider 8 | } 9 | 10 | create(address: string, abi: InterfaceAbi, signer?: Wallet | VoidSigner): Contract { 11 | return new Contract(address, abi, signer ?? this.provider) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/utils/extraWait.ts: -------------------------------------------------------------------------------- 1 | import { INestApplication } from '@nestjs/common' 2 | import { FastifyAdapter } from '@nestjs/platform-fastify' 3 | import { Adapter } from './platforms' 4 | 5 | export async function extraWait(adapter: Adapter, app: INestApplication) { 6 | if (adapter === FastifyAdapter) { 7 | const instance = app.getHttpAdapter().getInstance() 8 | if (instance && typeof instance.ready === 'function') { 9 | await instance.ready() 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ethers.decorators.ts: -------------------------------------------------------------------------------- 1 | import { Inject } from '@nestjs/common' 2 | import { getContractToken, getEthersToken, getSignerToken } from './ethers.utils' 3 | 4 | export const InjectEthersProvider = (token?: string) => { 5 | return Inject(getEthersToken(token)) 6 | } 7 | 8 | export const InjectContractProvider = (token?: string) => { 9 | return Inject(getContractToken(token)) 10 | } 11 | 12 | export const InjectSignerProvider = (token?: string) => { 13 | return Inject(getSignerToken(token)) 14 | } 15 | -------------------------------------------------------------------------------- /src/ethers.module.ts: -------------------------------------------------------------------------------- 1 | import { Module, DynamicModule } from '@nestjs/common' 2 | import { EthersCoreModule } from './ethers-core.module' 3 | import { EthersModuleOptions, EthersModuleAsyncOptions } from './ethers.interface' 4 | 5 | @Module({}) 6 | export class EthersModule { 7 | static forRoot(options: EthersModuleOptions = {}): DynamicModule { 8 | return { 9 | module: EthersModule, 10 | imports: [EthersCoreModule.forRoot(options)], 11 | } 12 | } 13 | 14 | static forRootAsync(options: EthersModuleAsyncOptions): DynamicModule { 15 | return { 16 | module: EthersModule, 17 | imports: [EthersCoreModule.forRootAsync(options)], 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "strict": true, 15 | "noImplicitAny": true, 16 | "alwaysStrict": true, 17 | "strictNullChecks": true, 18 | "noImplicitReturns": true, 19 | "noImplicitThis": true, 20 | "noUnusedLocals": true, 21 | "noFallthroughCasesInSwitch": true, 22 | "resolveJsonModule": true, 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /test/utils/appRequest.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core' 2 | import * as request from 'supertest' 3 | import { Test } from 'tap' 4 | import { NEST_APP_OPTIONS } from './constants' 5 | import { extraWait } from './extraWait' 6 | import { Adapter } from './platforms' 7 | 8 | export async function appRequest(t: Test, module: any, httpAdapter: Adapter): Promise { 9 | const adapterInstance = new httpAdapter() 10 | const app = await NestFactory.create(module, adapterInstance, NEST_APP_OPTIONS) 11 | 12 | t.teardown(async () => { 13 | await app.close() 14 | }) 15 | 16 | const server = app.getHttpServer() 17 | 18 | await app.init() 19 | 20 | await extraWait(httpAdapter, app) 21 | 22 | return request(server).get('/') 23 | } 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. [Fork it](https://help.github.com/articles/fork-a-repo/) 4 | 2. Install dependencies (`npm install`) 5 | 3. Create your feature branch (`git checkout -b my-new-feature`) 6 | 4. Commit your changes (`git commit -am 'Added some feature'`) 7 | 5. Test your changes (`npm test`) 8 | 6. Push to the branch (`git push origin my-new-feature`) 9 | 7. [Create new Pull Request](https://help.github.com/articles/creating-a-pull-request/) 10 | 11 | ## Testing 12 | 13 | We use [Jest](https://github.com/facebook/jest) to write tests. Run our test suite with this command: 14 | 15 | ``` 16 | npm test 17 | ``` 18 | 19 | ## Code Style 20 | 21 | We use [Prettier](https://prettier.io/) and tslint to maintain code style and best practices. 22 | Please make sure your PR adheres to the guides by running: 23 | 24 | ``` 25 | npm run format 26 | ``` 27 | 28 | and 29 | ``` 30 | npm run lint 31 | ``` -------------------------------------------------------------------------------- /src/ethers.signer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | VoidSigner, 3 | BytesLike, 4 | ProgressCallback, 5 | AbstractProvider, 6 | SigningKey, 7 | Wallet, 8 | HDNodeWallet, 9 | Mnemonic, 10 | } from 'ethers' 11 | 12 | export class EthersSigner { 13 | private readonly provider: AbstractProvider 14 | 15 | constructor(provider: AbstractProvider) { 16 | this.provider = provider 17 | } 18 | 19 | createWallet(privateKey: string | SigningKey): Wallet { 20 | return new Wallet(privateKey, this.provider) 21 | } 22 | 23 | createRandomWallet(): HDNodeWallet { 24 | return Wallet.createRandom(this.provider) 25 | } 26 | 27 | async createWalletFromEncryptedJson( 28 | jsonString: string, 29 | password: BytesLike, 30 | progressCallback?: ProgressCallback, 31 | ): Promise { 32 | const wallet = await Wallet.fromEncryptedJson(jsonString, password, progressCallback) 33 | 34 | return wallet.connect(this.provider) 35 | } 36 | 37 | createWalletfromMnemonic(mnemonic: Mnemonic, path?: string): HDNodeWallet { 38 | const wallet = HDNodeWallet.fromMnemonic(mnemonic, path) 39 | 40 | return wallet.connect(this.provider) 41 | } 42 | 43 | createVoidSigner(address: string): VoidSigner { 44 | return new VoidSigner(address, this.provider) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## PR Checklist 2 | Please check if your PR fulfills the following requirements: 3 | 4 | - [ ] The commit message follows our guidelines: https://github.com/blockcoders/nestjs-ethers/blob/master/CONTRIBUTING.md 5 | - [ ] Tests for the changes have been added (for bug fixes / features) 6 | - [ ] Docs have been added / updated (for bug fixes / features) 7 | 8 | ## PR Type 9 | What kind of change does this PR introduce? 10 | 11 | 12 | - [ ] Bugfix 13 | - [ ] Feature 14 | - [ ] Code style update (formatting, local variables) 15 | - [ ] Refactoring (no functional changes, no api changes) 16 | - [ ] Build related changes 17 | - [ ] CI related changes 18 | - [ ] Other... Please describe: 19 | 20 | ## What is the current behavior? 21 | 22 | 23 | Issue Number: N/A 24 | 25 | ## What is the new behavior? 26 | 27 | 28 | 29 | ## Does this PR introduce a breaking change? 30 | 31 | - [ ] Yes 32 | - [ ] No 33 | 34 | 35 | 36 | ## Other information 37 | 38 | -------------------------------------------------------------------------------- /src/ethers.interface.ts: -------------------------------------------------------------------------------- 1 | import { ModuleMetadata } from '@nestjs/common/interfaces' 2 | import type { FetchRequest, Networkish } from 'ethers' 3 | 4 | export interface InfuraProviderOptions { 5 | projectId?: string 6 | projectSecret?: string 7 | } 8 | 9 | export interface PocketProviderOptions { 10 | applicationId?: string 11 | applicationSecretKey?: string 12 | } 13 | 14 | export interface MoralisProviderOptions { 15 | apiKey?: string 16 | region?: string 17 | } 18 | 19 | export interface ProviderOptions { 20 | alchemy?: string | undefined 21 | etherscan?: string | undefined 22 | bscscan?: string | undefined 23 | cloudflare?: boolean | undefined 24 | infura?: InfuraProviderOptions | undefined 25 | pocket?: PocketProviderOptions | undefined 26 | moralis?: MoralisProviderOptions | undefined 27 | ankr?: string | undefined 28 | custom?: (string | FetchRequest) | (string | FetchRequest)[] | undefined 29 | quorum?: number | undefined 30 | } 31 | 32 | export interface EthersModuleOptions extends ProviderOptions { 33 | network?: Networkish | undefined 34 | token?: string | undefined 35 | useDefaultProvider?: boolean | undefined 36 | } 37 | 38 | export interface EthersModuleAsyncOptions extends Pick { 39 | token?: string | undefined 40 | useFactory: (...args: any[]) => Omit | Promise> 41 | inject?: any[] 42 | } 43 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | ## I'm submitting a... 8 | 11 |

12 | [ ] Regression 
13 | [ ] Bug report
14 | [ ] Feature request
15 | [ ] Documentation issue or request
16 | [ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
17 | 
18 | 19 | ## Current behavior 20 | 21 | 22 | 23 | ## Expected behavior 24 | 25 | 26 | 27 | ## Minimal reproduction of the problem with instructions 28 | 29 | 30 | ## What is the motivation / use case for changing the behavior? 31 | 32 | 33 | ## Environment 34 | 35 |

36 | Nest version: X.Y.Z
37 | Nest Ethers version: X.Y.Z
38 | 
39 |  
40 | For Tooling issues:
41 | - Node version: XX  
42 | - Platform:  
43 | - Server:  
44 | 
45 | Others:
46 | 
47 | 
48 | -------------------------------------------------------------------------------- /src/ethers.utils.ts: -------------------------------------------------------------------------------- 1 | import { Network, Networkish } from 'ethers' 2 | import { 3 | BINANCE_NETWORK, 4 | BINANCE_TESTNET_NETWORK, 5 | DECORATED_PREFIX, 6 | DEFAULT_TOKEN, 7 | NETWORKS_BY_CHAIN_ID, 8 | NETWORKS_BY_NAME, 9 | UNSPECIFIED_NETWORK, 10 | } from './ethers.constants' 11 | 12 | export function getEthersToken(token?: string): string { 13 | return `${DECORATED_PREFIX}:Provider:${token || DEFAULT_TOKEN}` 14 | } 15 | 16 | export function getContractToken(token?: string): string { 17 | return `${DECORATED_PREFIX}:Contract:${token || DEFAULT_TOKEN}` 18 | } 19 | 20 | export function getSignerToken(token?: string): string { 21 | return `${DECORATED_PREFIX}:Signer:${token || DEFAULT_TOKEN}` 22 | } 23 | 24 | export function getNetwork(network?: Networkish): Network { 25 | if (!network) { 26 | throw new Error(`Invalid value: ${network}`) 27 | } 28 | 29 | if (typeof network === 'number' && NETWORKS_BY_CHAIN_ID.has(BigInt(network))) { 30 | return NETWORKS_BY_CHAIN_ID.get(BigInt(network)) as Network 31 | } 32 | 33 | if (typeof network === 'string' && NETWORKS_BY_NAME.has(network)) { 34 | return NETWORKS_BY_NAME.get(network) as Network 35 | } 36 | 37 | if (typeof network !== 'bigint' && typeof network !== 'number' && typeof network !== 'string' && network?.name) { 38 | return Network.from(network) 39 | } 40 | 41 | return UNSPECIFIED_NETWORK 42 | } 43 | 44 | export function isBinanceNetwork(network: Network): boolean { 45 | switch (network.name) { 46 | case BINANCE_NETWORK.name: 47 | case BINANCE_TESTNET_NETWORK.name: 48 | return true 49 | default: 50 | return false 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | const { fixupPluginRules } = require('@eslint/compat') 2 | const { FlatCompat } = require('@eslint/eslintrc') 3 | const js = require('@eslint/js') 4 | const tsParser = require('@typescript-eslint/parser') 5 | const _import = require('eslint-plugin-import') 6 | const globals = require('globals') 7 | 8 | const compat = new FlatCompat({ 9 | baseDirectory: __dirname, 10 | recommendedConfig: js.configs.recommended, 11 | allConfig: js.configs.all, 12 | }) 13 | 14 | module.exports = [ 15 | { 16 | ignores: ['**/eslint.config.js', '**/dist/**', '**/node_modules/**'], 17 | }, 18 | ...compat.extends('plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended'), 19 | { 20 | plugins: { 21 | import: fixupPluginRules(_import), 22 | }, 23 | 24 | languageOptions: { 25 | globals: { 26 | ...globals.node, 27 | ...globals.jest, 28 | }, 29 | 30 | parser: tsParser, 31 | ecmaVersion: 5, 32 | sourceType: 'module', 33 | 34 | parserOptions: { 35 | project: 'tsconfig.json', 36 | }, 37 | }, 38 | 39 | rules: { 40 | '@typescript-eslint/interface-name-prefix': 'off', 41 | '@typescript-eslint/explicit-function-return-type': 'off', 42 | '@typescript-eslint/explicit-module-boundary-types': 'off', 43 | '@typescript-eslint/no-explicit-any': 'off', 44 | 45 | 'import/order': [ 46 | 'error', 47 | { 48 | alphabetize: { 49 | order: 'asc', 50 | }, 51 | 52 | groups: [ 53 | ['builtin', 'external'], 54 | ['internal', 'parent', 'sibling', 'index'], 55 | ], 56 | 'newlines-between': 'never', 57 | }, 58 | ], 59 | }, 60 | }, 61 | ] 62 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Use the latest 2.1 version of CircleCI pipeline process engine. 2 | # See: https://circleci.com/docs/2.0/configuration-reference 3 | version: 2.1 4 | 5 | orbs: 6 | # The Node.js orb contains a set of prepackaged CircleCI configuration you can utilize 7 | # Orbs reduce the amount of configuration required for common tasks. 8 | # See the orb documentation here: https://circleci.com/developer/orbs/orb/circleci/node 9 | node: circleci/node@5.0.3 10 | coveralls: coveralls/coveralls@1.0.6 11 | 12 | jobs: 13 | test: 14 | parameters: 15 | node-version: 16 | type: string 17 | docker: 18 | - image: cimg/node:<< parameters.node-version >> 19 | resource_class: small 20 | steps: 21 | - checkout 22 | - restore_cache: 23 | # See the configuration reference documentation for more details on using restore_cache and save_cache steps 24 | # https://circleci.com/docs/2.0/configuration-reference/?section=reference#save_cache 25 | keys: 26 | - node-deps-v1-{{ .Branch }}-{{checksum "package-lock.json"}} 27 | - run: 28 | name: install packages 29 | command: npm ci 30 | - save_cache: 31 | key: node-deps-v1-{{ .Branch }}-{{checksum "package-lock.json"}} 32 | paths: 33 | - ~/.npm 34 | - run: 35 | name: Run Lint 36 | command: npm run lint:ci 37 | - run: 38 | name: Run Tests 39 | command: npm run test:cov 40 | - run: 41 | name: Run Build 42 | command: npm run build 43 | - coveralls/upload: 44 | path_to_lcov: .tap/report/lcov.info 45 | verbose: true 46 | 47 | workflows: 48 | test-workflow: 49 | jobs: 50 | - test: 51 | matrix: 52 | parameters: 53 | node-version: ['22.10', '20.17', '18.20'] 54 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-ethers", 3 | "version": "3.0.1", 4 | "description": "The ethers.js library for NestJS", 5 | "author": "Blockcoders Engineering ", 6 | "license": "Apache", 7 | "readmeFilename": "README.md", 8 | "main": "dist/index.js", 9 | "engineStrict": false, 10 | "engines": { 11 | "node": "^18.x || >=20.x || >=22.x" 12 | }, 13 | "scripts": { 14 | "build": "rm -rf ./dist && tsc --p tsconfig.build.json", 15 | "prepare": "npm run build", 16 | "format": "prettier --write \"src/**/*.ts\"", 17 | "lint": "eslint \"{src,apps,libs,test,__tests__}/**/*.ts\" --fix", 18 | "lint:ci": "eslint \"{src,apps,libs,test,__tests__}/**/*.ts\"", 19 | "test": "tap --passes test/*.spec.ts", 20 | "test:cov": "tap test/*.spec.ts --coverage-report=text-summary --coverage-report=lcovonly --allow-incomplete-coverage" 21 | }, 22 | "precommit": [ 23 | "lint:ci", 24 | "test:cov" 25 | ], 26 | "keywords": [ 27 | "ethers", 28 | "ethers.js", 29 | "ethereum", 30 | "nestjs", 31 | "nest.js", 32 | "nest", 33 | "blockchain" 34 | ], 35 | "publishConfig": { 36 | "access": "public" 37 | }, 38 | "repository": { 39 | "type": "git", 40 | "url": "https://github.com/blockcoders/nestjs-ethers" 41 | }, 42 | "homepage": "https://github.com/blockcoders/nestjs-ethers/blob/main/README.md", 43 | "bugs": "https://github.com/blockcoders/nestjs-ethers/issues", 44 | "devDependencies": { 45 | "@eslint/compat": "^2.0.0", 46 | "@fastify/pre-commit": "^2.2.1", 47 | "@nestjs/common": "^11.1.9", 48 | "@nestjs/core": "^11.1.9", 49 | "@nestjs/platform-express": "^11.1.9", 50 | "@nestjs/platform-fastify": "^11.1.9", 51 | "@types/node": "^24.6.1", 52 | "@types/supertest": "^6.0.3", 53 | "@typescript-eslint/eslint-plugin": "^8.50.0", 54 | "@typescript-eslint/parser": "^8.50.0", 55 | "eslint": "^9.39.2", 56 | "eslint-config-prettier": "^10.1.8", 57 | "eslint-plugin-import": "^2.32.0", 58 | "eslint-plugin-prettier": "^5.5.4", 59 | "ethers": "^6.16.0", 60 | "nock": "^14.0.10", 61 | "prettier": "^3.7.4", 62 | "rxjs": "^7.8.2", 63 | "supertest": "^7.1.4", 64 | "tap": "^21.5.0", 65 | "typescript": "^5.9.3" 66 | }, 67 | "peerDependencies": { 68 | "@nestjs/common": "^11.1.6", 69 | "ethers": "^6.15.0" 70 | }, 71 | "tap": { 72 | "diag": true, 73 | "bail": true, 74 | "comments": true, 75 | "timeout": 40000 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | .tap 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # TypeScript v1 declaration files 46 | typings/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Microbundle cache 58 | .rpt2_cache/ 59 | .rts2_cache_cjs/ 60 | .rts2_cache_es/ 61 | .rts2_cache_umd/ 62 | 63 | # Optional REPL history 64 | .node_repl_history 65 | 66 | # Output of 'npm pack' 67 | *.tgz 68 | 69 | # Yarn Integrity file 70 | .yarn-integrity 71 | 72 | # dotenv environment variables file 73 | .env 74 | .env.test 75 | 76 | # parcel-bundler cache (https://parceljs.org/) 77 | .cache 78 | 79 | # Next.js build output 80 | .next 81 | 82 | # Nuxt.js build / generate output 83 | .nuxt 84 | dist 85 | 86 | # Gatsby files 87 | .cache/ 88 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 89 | # https://nextjs.org/blog/next-9-1#public-directory-support 90 | # public 91 | 92 | # vuepress build output 93 | .vuepress/dist 94 | 95 | # Serverless directories 96 | .serverless/ 97 | 98 | # FuseBox cache 99 | .fusebox/ 100 | 101 | # DynamoDB Local files 102 | .dynamodb/ 103 | 104 | # TernJS port file 105 | .tern-port 106 | 107 | # compiled output 108 | /dist 109 | /node_modules 110 | 111 | # OS 112 | .DS_Store 113 | 114 | # Tests 115 | /coverage 116 | /.nyc_output 117 | 118 | # IDEs and editors 119 | /.idea 120 | .project 121 | .classpath 122 | .c9/ 123 | *.launch 124 | .settings/ 125 | *.sublime-workspace 126 | 127 | # IDE - VSCode 128 | .vscode/* 129 | !.vscode/settings.json 130 | !.vscode/tasks.json 131 | !.vscode/launch.json 132 | !.vscode/extensions.json -------------------------------------------------------------------------------- /src/ethers-core.module.ts: -------------------------------------------------------------------------------- 1 | import { DynamicModule, Global, Module, OnApplicationShutdown } from '@nestjs/common' 2 | import { DiscoveryModule, DiscoveryService } from '@nestjs/core' 3 | import { AbstractProvider } from 'ethers' 4 | import { EthersContract } from './ethers.contract' 5 | import { EthersModuleAsyncOptions, EthersModuleOptions } from './ethers.interface' 6 | import { 7 | createAsyncOptionsProvider, 8 | createContractProvider, 9 | createEthersAsyncProvider, 10 | createEthersProvider, 11 | createSignerProvider, 12 | } from './ethers.providers' 13 | import { EthersSigner } from './ethers.signer' 14 | 15 | @Global() 16 | @Module({}) 17 | export class EthersCoreModule implements OnApplicationShutdown { 18 | constructor(private readonly discoveryService: DiscoveryService) {} 19 | 20 | static forRoot(options: EthersModuleOptions): DynamicModule { 21 | const ethersProvider = createEthersProvider(options) 22 | const contractProvider = createContractProvider(options.token) 23 | const signerProvider = createSignerProvider(options.token) 24 | 25 | return { 26 | module: EthersCoreModule, 27 | imports: [DiscoveryModule], 28 | providers: [EthersSigner, EthersContract, ethersProvider, contractProvider, signerProvider], 29 | exports: [EthersSigner, EthersContract, ethersProvider, contractProvider, signerProvider], 30 | } 31 | } 32 | 33 | static forRootAsync(options: EthersModuleAsyncOptions): DynamicModule { 34 | const ethersProvider = createEthersAsyncProvider(options.token) 35 | const asyncOptionsProvider = createAsyncOptionsProvider(options) 36 | const contractProvider = createContractProvider(options.token) 37 | const signerProvider = createSignerProvider(options.token) 38 | 39 | return { 40 | module: EthersCoreModule, 41 | imports: [DiscoveryModule, ...(options.imports || [])], 42 | providers: [ 43 | EthersSigner, 44 | EthersContract, 45 | asyncOptionsProvider, 46 | ethersProvider, 47 | contractProvider, 48 | signerProvider, 49 | ...(options.providers || []), 50 | ], 51 | exports: [EthersSigner, EthersContract, ethersProvider, contractProvider, signerProvider], 52 | } 53 | } 54 | 55 | async onApplicationShutdown() { 56 | const providers = this.discoveryService.getProviders() ?? [] 57 | 58 | providers.forEach((provider) => { 59 | const { instance } = provider ?? {} 60 | 61 | if (provider.isDependencyTreeStatic() && instance && instance instanceof AbstractProvider) { 62 | instance.removeAllListeners() 63 | } 64 | }) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "main" ] 20 | schedule: 21 | - cron: '20 7 * * 0' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'TypeScript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | 52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 53 | # queries: security-extended,security-and-quality 54 | 55 | 56 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 57 | # If this step fails, then you should remove it and run the build manually (see below) 58 | - name: Autobuild 59 | uses: github/codeql-action/autobuild@v2 60 | 61 | # ℹ️ Command-line programs to run using the OS shell. 62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 63 | 64 | # If the Autobuild fails above, remove it and uncomment the following three lines. 65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 66 | 67 | # - run: | 68 | # echo "Run, Build Application using script" 69 | # ./location_of_script_within_repo/buildscript.sh 70 | 71 | - name: Perform CodeQL Analysis 72 | uses: github/codeql-action/analyze@v2 73 | with: 74 | category: "/language:${{matrix.language}}" 75 | -------------------------------------------------------------------------------- /test/utils/ABI.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "anonymous": false, 4 | "inputs": [ 5 | { 6 | "indexed": true, 7 | "internalType": "uint256", 8 | "name": "proposalId", 9 | "type": "uint256" 10 | }, 11 | { 12 | "indexed": true, 13 | "internalType": "address", 14 | "name": "from", 15 | "type": "address" 16 | }, 17 | { 18 | "indexed": false, 19 | "internalType": "uint256", 20 | "name": "vote", 21 | "type": "uint256" 22 | } 23 | ], 24 | "name": "VoteCasted", 25 | "type": "event" 26 | }, 27 | { 28 | "constant": true, 29 | "inputs": [], 30 | "name": "VOTE_FEE", 31 | "outputs": [ 32 | { 33 | "internalType": "uint256", 34 | "name": "", 35 | "type": "uint256" 36 | } 37 | ], 38 | "payable": false, 39 | "stateMutability": "view", 40 | "type": "function" 41 | }, 42 | { 43 | "constant": false, 44 | "inputs": [], 45 | "name": "clean", 46 | "outputs": [], 47 | "payable": false, 48 | "stateMutability": "nonpayable", 49 | "type": "function" 50 | }, 51 | { 52 | "constant": true, 53 | "inputs": [ 54 | { 55 | "internalType": "address", 56 | "name": "_user", 57 | "type": "address" 58 | } 59 | ], 60 | "name": "getVote", 61 | "outputs": [ 62 | { 63 | "internalType": "uint256", 64 | "name": "", 65 | "type": "uint256" 66 | } 67 | ], 68 | "payable": false, 69 | "stateMutability": "view", 70 | "type": "function" 71 | }, 72 | { 73 | "constant": true, 74 | "inputs": [], 75 | "name": "proposalId", 76 | "outputs": [ 77 | { 78 | "internalType": "uint256", 79 | "name": "", 80 | "type": "uint256" 81 | } 82 | ], 83 | "payable": false, 84 | "stateMutability": "view", 85 | "type": "function" 86 | }, 87 | { 88 | "constant": false, 89 | "inputs": [ 90 | { 91 | "internalType": "uint256", 92 | "name": "_vote", 93 | "type": "uint256" 94 | } 95 | ], 96 | "name": "vote", 97 | "outputs": [], 98 | "payable": true, 99 | "stateMutability": "payable", 100 | "type": "function" 101 | }, 102 | { 103 | "constant": true, 104 | "inputs": [], 105 | "name": "votesForNo", 106 | "outputs": [ 107 | { 108 | "internalType": "uint256", 109 | "name": "", 110 | "type": "uint256" 111 | } 112 | ], 113 | "payable": false, 114 | "stateMutability": "view", 115 | "type": "function" 116 | }, 117 | { 118 | "constant": true, 119 | "inputs": [], 120 | "name": "votesForYes", 121 | "outputs": [ 122 | { 123 | "internalType": "uint256", 124 | "name": "", 125 | "type": "uint256" 126 | } 127 | ], 128 | "payable": false, 129 | "stateMutability": "view", 130 | "type": "function" 131 | } 132 | ] -------------------------------------------------------------------------------- /test/ethers.utils.spec.ts: -------------------------------------------------------------------------------- 1 | import t from 'tap' 2 | import { 3 | BINANCE_NETWORK, 4 | BINANCE_TESTNET_NETWORK, 5 | DECORATED_PREFIX, 6 | DEFAULT_TOKEN, 7 | MAINNET_NETWORK, 8 | SEPOLIA_NETWORK, 9 | UNSPECIFIED_NETWORK, 10 | } from '../src/ethers.constants' 11 | import { getContractToken, getEthersToken, getNetwork, getSignerToken, isBinanceNetwork } from '../src/ethers.utils' 12 | 13 | t.test('getEthersToken', (t) => { 14 | t.test('should return a default ethers token', (t) => { 15 | t.equal(getEthersToken(), `${DECORATED_PREFIX}:Provider:${DEFAULT_TOKEN}`) 16 | t.end() 17 | }) 18 | 19 | t.test('should return a custom ethers token', (t) => { 20 | t.equal(getEthersToken('custom'), `${DECORATED_PREFIX}:Provider:custom`) 21 | t.end() 22 | }) 23 | 24 | t.end() 25 | }) 26 | 27 | t.test('getContractToken', (t) => { 28 | t.test('should return a default contract token', (t) => { 29 | t.equal(getContractToken(), `${DECORATED_PREFIX}:Contract:${DEFAULT_TOKEN}`) 30 | t.end() 31 | }) 32 | 33 | t.test('should return a custom contract token', (t) => { 34 | t.equal(getContractToken('custom'), `${DECORATED_PREFIX}:Contract:custom`) 35 | t.end() 36 | }) 37 | 38 | t.end() 39 | }) 40 | 41 | t.test('getSignerToken', (t) => { 42 | t.test('should return a default signer token', (t) => { 43 | t.equal(getSignerToken(), `${DECORATED_PREFIX}:Signer:${DEFAULT_TOKEN}`) 44 | t.end() 45 | }) 46 | 47 | t.test('should return a custom signer token', (t) => { 48 | t.equal(getSignerToken('custom'), `${DECORATED_PREFIX}:Signer:custom`) 49 | t.end() 50 | }) 51 | 52 | t.end() 53 | }) 54 | 55 | t.test('getNetwork', (t) => { 56 | t.test('should return a valid network', (t) => { 57 | const network = getNetwork(1) 58 | 59 | t.equal(network, MAINNET_NETWORK) 60 | t.end() 61 | }) 62 | 63 | t.test('should return a UNSPECIFIED_NETWORK network', (t) => { 64 | const network = getNetwork(-1) 65 | 66 | t.equal(network, UNSPECIFIED_NETWORK) 67 | t.end() 68 | }) 69 | 70 | t.test('should throw an error if the network is not defined', (t) => { 71 | t.throws(() => getNetwork()) 72 | t.end() 73 | }) 74 | 75 | t.test('should return a valid network for a chainId', (t) => { 76 | const network = getNetwork(11155111) 77 | 78 | t.equal(network, SEPOLIA_NETWORK) 79 | t.end() 80 | }) 81 | 82 | t.test('should return a valid network for a name', (t) => { 83 | const network = getNetwork('sepolia') 84 | t.equal(network.name, SEPOLIA_NETWORK.name) 85 | t.end() 86 | }) 87 | 88 | t.test('should return a valid network for a Network object', (t) => { 89 | const network = getNetwork(SEPOLIA_NETWORK) 90 | 91 | t.equal(network.name, SEPOLIA_NETWORK.name) 92 | t.end() 93 | }) 94 | 95 | t.end() 96 | }) 97 | 98 | t.test('isBinanceNetwork', (t) => { 99 | t.test('should return true for BINANCE_NETWORK', (t) => { 100 | t.equal(isBinanceNetwork(BINANCE_NETWORK), true) 101 | t.end() 102 | }) 103 | 104 | t.test('should return true for BINANCE_TESTNET_NETWORK', (t) => { 105 | t.equal(isBinanceNetwork(BINANCE_TESTNET_NETWORK), true) 106 | t.end() 107 | }) 108 | 109 | t.test('should return false for non binance networks', async (t) => { 110 | t.equal(isBinanceNetwork(MAINNET_NETWORK), false) 111 | t.end() 112 | }) 113 | 114 | t.end() 115 | }) 116 | -------------------------------------------------------------------------------- /test/utils/constants.ts: -------------------------------------------------------------------------------- 1 | import { NestApplicationOptions } from '@nestjs/common' 2 | import { randomBytes } from 'crypto' 3 | 4 | export const GOERLI_ALCHEMY_URL = 'https://eth-goerli.g.alchemy.com' 5 | export const GOERLI_POCKET_URL = 'https://eth-goerli.gateway.pokt.network/v1/lb/' 6 | export const BSC_POCKET_URL = 'https://bsc-mainnet.gateway.pokt.network/v1/lb' 7 | export const GOERLI_INFURA_URL = 'https://goerli.infura.io/v3' 8 | export const CLOUDFLARE_URL = 'https://cloudflare-eth.com' 9 | export const ETHERSCAN_V2_URL = 'https://api.etherscan.io' 10 | export const TESTNET_BSCPOCKET_URL = 'https://bsc-testnet.gateway.pokt.network/v1/lb' 11 | export const CUSTOM_BSC_1_URL = 'https://data-seed-prebsc-1-s1.binance.org:8545' 12 | export const CUSTOM_BSC_2_URL = 'https://data-seed-prebsc-1-s3.binance.org:8545' 13 | export const CUSTOM_BSC_3_URL = 'https://data-seed-prebsc-2-s2.binance.org:8545' 14 | export const MUMBAI_ALCHEMY_URL = 'https://polygon-mumbai.g.alchemy.com/v2/' 15 | export const POLYGON_TESTNET_GASSTATION_URL = 'https://gasstation-testnet.polygon.technology' 16 | export const GOERLI_QUICKNODE_URL = 'https://ethers.ethereum-goerli.quiknode.pro' 17 | export const GOERLI_QUICKNODE_TOKEN = '919b412a057b5e9c9b6dce193c5a60242d6efadb' 18 | export const GOERLI_ETHERSCAN_API_KEY = randomBytes(17).toString('hex') 19 | export const GOERLI_ALCHEMY_API_KEY = randomBytes(16).toString('hex') 20 | export const GOERLI_POKT_API_KEY = { 21 | applicationId: randomBytes(12).toString('hex'), 22 | applicationSecretKey: randomBytes(16).toString('hex'), 23 | } 24 | export const GOERLI_INFURA_PROJECT_ID = randomBytes(16).toString('hex') 25 | export const GOERLI_INFURA_PROJECT_SECRET = randomBytes(16).toString('hex') 26 | export const GOERLI_MORALIS_API_KEY = { apiKey: randomBytes(12).toString('hex') } 27 | export const GOERLI_MORALIS_URL = `https://speedy-nodes-nyc.moralis.io/${GOERLI_MORALIS_API_KEY.apiKey}/eth/goerli` 28 | export const BINANCE_TESTNET_MORALIS_API_KEY = { apiKey: randomBytes(12).toString('hex') } 29 | export const BINANCE_TESTNET_MORALIS_URL = `https://speedy-nodes-nyc.moralis.io/${BINANCE_TESTNET_MORALIS_API_KEY.apiKey}/bsc/testnet` 30 | export const GOERLI_ANKR_API_KEY = randomBytes(12).toString('hex') 31 | export const GOERLI_ANKR_URL = `https://rpc.ankr.com/eth_goerli/${GOERLI_ANKR_API_KEY}` 32 | export const ETHERS_ADDRESS = '0x012363d61bdc53d0290a0f25e9c89f8257550fb8' 33 | export const ETHERS_PRIVATE_KEY = '0x4c94faa2c558a998d10ee8b2b9b8eb1fbcb8a6ac5fd085c6f95535604fc1bffb' 34 | export const ETHERS_MNEMONIC = 'service basket parent alcohol fault similar survey twelve hockey cloud walk panel' 35 | export const ETHERS_JSON_WALLET_PASSWORD = 'password' 36 | export const ETHERS_JSON_WALLET = JSON.stringify({ 37 | address: '012363d61bdc53d0290a0f25e9c89f8257550fb8', 38 | id: '5ba8719b-faf9-49ec-8bca-21522e3d56dc', 39 | version: 3, 40 | Crypto: { 41 | cipher: 'aes-128-ctr', 42 | cipherparams: { iv: 'bc0473d60284d2d6994bb6793e916d06' }, 43 | ciphertext: 'e73ed0b0c53bcaea4516a15faba3f6d76dbe71b9b46a460ed7e04a68e0867dd7', 44 | kdf: 'scrypt', 45 | kdfparams: { 46 | salt: '97f0b6e17c392f76a726ceea02bac98f17265f1aa5cf8f9ad1c2b56025bc4714', 47 | n: 131072, 48 | dklen: 32, 49 | p: 1, 50 | r: 8, 51 | }, 52 | mac: 'ff4f2db7e7588f8dd41374d7b98dfd7746b554c0099a6c0765be7b1c7913e1f3', 53 | }, 54 | 'x-ethers': { 55 | client: 'ethers.js', 56 | gethFilename: 'UTC--2018-01-27T01-52-22.0Z--012363d61bdc53d0290a0f25e9c89f8257550fb8', 57 | mnemonicCounter: '70224accc00e35328a010a19fef51121', 58 | mnemonicCiphertext: 'cf835e13e4f90b190052263dbd24b020', 59 | version: '0.1', 60 | }, 61 | }) 62 | 63 | export const NEST_APP_OPTIONS: NestApplicationOptions = { 64 | logger: false, 65 | abortOnError: false, 66 | } 67 | -------------------------------------------------------------------------------- /test/utils/mockResponses.ts: -------------------------------------------------------------------------------- 1 | import * as nock from 'nock' 2 | import { Body, ReplyBody, ReplyFnContext } from 'nock' 3 | import { ETHERSCAN_V2_URL } from './constants' 4 | 5 | export const GAS_STATION_RESPONSE = { 6 | safeLow: { 7 | maxPriorityFee: 25, 8 | maxFee: 25.000000069, 9 | }, 10 | standard: { 11 | maxPriorityFee: 25, 12 | maxFee: 25.000000069, 13 | }, 14 | fast: { 15 | maxPriorityFee: 25, 16 | maxFee: 25.000000069, 17 | }, 18 | estimatedBaseFee: 6.9e-8, 19 | blockTime: 2.5, 20 | blockNumber: 76294707, 21 | } 22 | export function generateMethodQuery( 23 | method: string, 24 | chainid: string, 25 | otherParams?: Record, 26 | apikey?: string, 27 | ): Record { 28 | const query: Record = { 29 | module: 'proxy', 30 | action: method, 31 | chainid: chainid, 32 | ...otherParams, 33 | } 34 | 35 | if (apikey) { 36 | query['apikey'] = apikey 37 | } 38 | return query 39 | } 40 | type RpcResponse = { jsonrpc: string; id?: number; result: any } 41 | export const RPC_RESPONSES: Record = { 42 | eth_chainId: { jsonrpc: '2.0', result: '0x61' }, 43 | eth_blockNumber: { jsonrpc: '2.0', result: '0x802f1c' }, 44 | eth_getBlockByNumber: { 45 | jsonrpc: '2.0', 46 | id: 1, 47 | result: { 48 | baseFeePerGas: '0x989680', 49 | difficulty: '0x1', 50 | extraData: '0xc34336c52abd0d966f6edd330215fc30f1bdda37141f62c09392fd47b87094c3', 51 | gasLimit: '0x4000000000000', 52 | gasUsed: '0x3d1f9b', 53 | hash: '0xf79744d03488d866c9088cc7c9ed2cec03189fdda2eb723faae2863b6c0067b0', 54 | l1BlockNumber: '0x1640ae3', 55 | logsBloom: '0x00000001', 56 | miner: '0xa4b000000000000000000073657175656e636572', 57 | mixHash: '0x0000000000024f4d0000000001640ae300000000000000280000000000000000', 58 | nonce: '0x0000000000204044', 59 | number: '0x16839455', 60 | parentHash: '0x8f751e9d4f93fb93c60f8ebbc04ea1d592efff2b87e43d318b60fea806880c9f', 61 | receiptsRoot: '0x34bc4d09388576979c78376d2bc736a714b294eb9935e460cb098d7ecd2b30bd', 62 | sendCount: '0x24f4d', 63 | sendRoot: '0xc34336c52abd0d966f6edd330215fc30f1bdda37141f62c09392fd47b87094c3', 64 | sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 65 | size: '0x17f3', 66 | stateRoot: '0x0b0fe88a4155f1b4e2dfbd7fda0e066b80daad471fa69bcd2a6fdc2ba0cb9b6d', 67 | timestamp: '0x68c19ab9', 68 | transactions: [ 69 | '0xbb234fd1f66abe20e4b7ef01ddcd6ceb9ceb323fe9e2a5921d63f34398f1013f', 70 | '0xc93317b2598996d35899185bcea386eb841b189da78a8e1617965002cd0a0fcb', 71 | ], 72 | transactionsRoot: '0x2f974cb01f1219fd702e8cfd1b275c4e0fb7e60ebab07a0d57e6cbe358d76628', 73 | uncles: [], 74 | }, 75 | }, 76 | eth_maxPriorityFeePerGas: { 77 | jsonrpc: '2.0', 78 | result: '0x5f5e100', 79 | }, 80 | eth_gasPrice: { 81 | jsonrpc: '2.0', 82 | result: '0x3b9aca00', 83 | }, 84 | } 85 | 86 | export function matchResponses(this: ReplyFnContext, uri: string, requestBody: Body): ReplyBody | Promise { 87 | const body = typeof requestBody === 'string' ? JSON.parse(requestBody) : requestBody 88 | 89 | // Handle single request 90 | if (!Array.isArray(body)) { 91 | return { 92 | ...RPC_RESPONSES[body.method], 93 | id: body.id, // ensure request id matches 94 | } 95 | } 96 | 97 | // Handle batch request 98 | return body.map((req: any) => ({ 99 | ...RPC_RESPONSES[req.method], 100 | id: req.id, 101 | })) 102 | } 103 | export function nockAllRPCRequests() { 104 | nock('http://www.whatever-here.com', { 105 | filteringScope: function (scope) { 106 | const isPostRequestEndpoint = !scope.includes('127.0.0.1') && !scope.includes(ETHERSCAN_V2_URL) 107 | return isPostRequestEndpoint 108 | }, 109 | }) 110 | .persist() 111 | .post(/.*/) 112 | .reply(200, matchResponses) 113 | nock(ETHERSCAN_V2_URL) 114 | .persist() 115 | .get('/v2/api') 116 | .query((query) => query.action === 'eth_blockNumber') 117 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 118 | nock(ETHERSCAN_V2_URL) 119 | .persist() 120 | .get('/v2/api') 121 | .query((query) => query.action === 'eth_getBlockByNumber') 122 | .reply(200, RPC_RESPONSES['eth_getBlockByNumber']) 123 | nock(ETHERSCAN_V2_URL) 124 | .persist() 125 | .get('/v2/api') 126 | .query((query) => query.action === 'eth_gasPrice') 127 | .reply(200, RPC_RESPONSES['eth_gasPrice']) 128 | nock(ETHERSCAN_V2_URL) 129 | .persist() 130 | .get('/v2/api') 131 | .query((query) => query.action === 'eth_chainId') 132 | .reply(200, RPC_RESPONSES['eth_chainId']) 133 | nock(ETHERSCAN_V2_URL) 134 | .persist() 135 | .get('/v2/api') 136 | .query((query) => query.action === 'eth_maxPriorityFeePerGas') 137 | .reply(200, RPC_RESPONSES['eth_maxPriorityFeePerGas']) 138 | } 139 | -------------------------------------------------------------------------------- /src/ethers.providers.ts: -------------------------------------------------------------------------------- 1 | import { Provider } from '@nestjs/common' 2 | import { 3 | AbstractProvider, 4 | AlchemyProvider, 5 | AnkrProvider, 6 | CloudflareProvider, 7 | EtherscanProvider, 8 | FetchRequest, 9 | InfuraProvider, 10 | JsonRpcProvider, 11 | PocketProvider, 12 | } from 'ethers' 13 | import { defer, lastValueFrom } from 'rxjs' 14 | import { ETHERS_MODULE_OPTIONS, MAINNET_NETWORK } from './ethers.constants' 15 | import { EthersContract } from './ethers.contract' 16 | import { 17 | BinancePocketProvider, 18 | BscscanProvider, 19 | getFallbackProvider, 20 | getNetworkDefaultProvider, 21 | MoralisProvider, 22 | } from './ethers.custom-rpcs' 23 | import { EthersModuleAsyncOptions, EthersModuleOptions } from './ethers.interface' 24 | import { EthersSigner } from './ethers.signer' 25 | import { getContractToken, getEthersToken, getNetwork, getSignerToken, isBinanceNetwork } from './ethers.utils' 26 | 27 | export async function createAbstractProvider( 28 | options: EthersModuleOptions, 29 | ): Promise { 30 | const { 31 | network = MAINNET_NETWORK, 32 | quorum = 1, 33 | useDefaultProvider = true, 34 | alchemy, 35 | etherscan, 36 | bscscan, 37 | infura, 38 | pocket, 39 | moralis, 40 | ankr, 41 | cloudflare = false, 42 | custom, 43 | } = options 44 | 45 | const providerNetwork = getNetwork(network) 46 | 47 | if (!useDefaultProvider) { 48 | const providers: Array = [] 49 | 50 | if (alchemy) { 51 | providers.push(new AlchemyProvider(providerNetwork, alchemy)) 52 | } 53 | 54 | if (etherscan) { 55 | providers.push(new EtherscanProvider(providerNetwork, etherscan)) 56 | } 57 | 58 | if (bscscan) { 59 | providers.push(new BscscanProvider(providerNetwork, bscscan)) 60 | } 61 | 62 | if (infura) { 63 | providers.push(new InfuraProvider(providerNetwork, infura?.projectId, infura?.projectSecret)) 64 | } 65 | 66 | if (pocket) { 67 | if (isBinanceNetwork(providerNetwork)) { 68 | providers.push(new BinancePocketProvider(providerNetwork, pocket?.applicationId, pocket?.applicationSecretKey)) 69 | } else { 70 | providers.push(new PocketProvider(providerNetwork, pocket?.applicationId, pocket?.applicationSecretKey)) 71 | } 72 | } 73 | 74 | if (moralis) { 75 | providers.push(new MoralisProvider(providerNetwork, moralis?.apiKey, moralis?.region)) 76 | } 77 | 78 | if (cloudflare) { 79 | if (providerNetwork.chainId !== MAINNET_NETWORK.chainId) { 80 | throw new Error(`Invalid network. Cloudflare only supports ${MAINNET_NETWORK.name}.`) 81 | } 82 | 83 | providers.push(new CloudflareProvider(providerNetwork)) 84 | } 85 | 86 | if (ankr) { 87 | providers.push(new AnkrProvider(providerNetwork, ankr)) 88 | } 89 | 90 | if (custom) { 91 | const customInfos: (string | FetchRequest)[] = !Array.isArray(custom) ? [custom] : custom 92 | 93 | customInfos.forEach((customInfo) => { 94 | providers.push(new JsonRpcProvider(customInfo, providerNetwork)) 95 | }) 96 | } 97 | 98 | return getFallbackProvider(providers, quorum) 99 | } 100 | 101 | /** 102 | * The default provider is the safest, easiest way to begin developing on Ethereum 103 | * It creates a FallbackProvider connected to as many backend services as possible. 104 | * @see {@link https://docs.ethers.org/v6/api/providers/#getDefaultProvider} 105 | */ 106 | return getNetworkDefaultProvider(providerNetwork, { 107 | alchemy, 108 | etherscan, 109 | bscscan, 110 | infura, 111 | pocket, 112 | moralis, 113 | ankr, 114 | quorum, 115 | }) 116 | } 117 | 118 | export function createEthersProvider(options: EthersModuleOptions): Provider { 119 | return { 120 | provide: getEthersToken(options.token), 121 | useFactory: async (): Promise => { 122 | return await lastValueFrom(defer(() => createAbstractProvider(options))) 123 | }, 124 | } 125 | } 126 | 127 | export function createEthersAsyncProvider(token?: string): Provider { 128 | return { 129 | provide: getEthersToken(token), 130 | useFactory: async (options: EthersModuleOptions): Promise => { 131 | return await lastValueFrom(defer(() => createAbstractProvider(options))) 132 | }, 133 | inject: [ETHERS_MODULE_OPTIONS], 134 | } 135 | } 136 | 137 | export function createAsyncOptionsProvider(options: EthersModuleAsyncOptions): Provider { 138 | return { 139 | provide: ETHERS_MODULE_OPTIONS, 140 | useFactory: options.useFactory, 141 | inject: options.inject || [], 142 | } 143 | } 144 | 145 | export function createContractProvider(token?: string): Provider { 146 | return { 147 | provide: getContractToken(token), 148 | useFactory: async (provider: AbstractProvider): Promise => { 149 | return await lastValueFrom(defer(async () => new EthersContract(provider))) 150 | }, 151 | inject: [getEthersToken(token)], 152 | } 153 | } 154 | 155 | export function createSignerProvider(token?: string): Provider { 156 | return { 157 | provide: getSignerToken(token), 158 | useFactory: async (provider: AbstractProvider): Promise => { 159 | return await lastValueFrom(defer(async () => new EthersSigner(provider))) 160 | }, 161 | inject: [getEthersToken(token)], 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/ethers.constants.ts: -------------------------------------------------------------------------------- 1 | import { Network } from 'ethers' 2 | 3 | export const DECORATED_PREFIX = 'EthersJS' 4 | export const ETHERS_MODULE_OPTIONS = 'EthersModuleOptions' 5 | export const DEFAULT_TOKEN = 'default' 6 | export const BSCSCAN_DEFAULT_API_KEY = 'EVTS3CU31AATZV72YQ55TPGXGMVIFUQ9M9' 7 | export const BINANCE_POCKET_DEFAULT_APP_ID = '6136201a7bad1500343e248d' 8 | export const MAINNET_NETWORK = Network.from('mainnet') 9 | export const UNSPECIFIED_NETWORK = new Network('unspecified', 0) 10 | export const GOERLI_NETWORK = Network.from('goerli') 11 | export const SEPOLIA_NETWORK = Network.from('sepolia') 12 | export const GNOSIS_NETWORK = Network.from('xdai') 13 | export const POLYGON_NETWORK = Network.from('matic') 14 | export const MUMBAI_NETWORK = Network.from('matic-mumbai') 15 | export const BINANCE_NETWORK = Network.from('bnb') 16 | export const BINANCE_TESTNET_NETWORK = Network.from('bnbt') 17 | export const OPTIMISM_NETWORK = Network.from('optimism') 18 | export const OPTIMISM_KOVAN_NETWORK = new Network('optimism-kovan', 69) 19 | export const OPTIMISM_GOERLI_NETWORK = Network.from('optimism-goerli') 20 | export const ARBITRUM_NETWORK = Network.from('arbitrum') 21 | export const ARBITRUM_RINKEBY_NETWORK = new Network('arbitrum', 421611) 22 | export const ARBITRUM_GOERLI_NETWORK = Network.from('arbitrum-goerli') 23 | export const AVALANCHE_NETWORK = new Network('avalanche', 43114) 24 | export const AVALANCHE_FUJI_NETWORK = new Network('avalanche-fuji', 43113) 25 | export const CRONOS_NETWORK = new Network('cronos', 25) 26 | export const CRONOS_TESTNET_NETWORK = new Network('cronos-testnet', 338) 27 | export const FANTOM_NETWORK = new Network('fantom', 250) 28 | export const FANTOM_TESTNET_NETWORK = new Network('fantom-testnet', 4002) 29 | export const AURORA_NETWORK = new Network('aurora', 1313161554) 30 | export const AURORA_BETA_NETWORK = new Network('aurora-beta', 1313161556) 31 | export const AURORA_TESTNET_NETWORK = new Network('aurora-testnet', 1313161555) 32 | 33 | const NETWORKS_BY_CHAIN_ID: Map = new Map() 34 | NETWORKS_BY_CHAIN_ID.set(MAINNET_NETWORK.chainId, MAINNET_NETWORK) 35 | NETWORKS_BY_CHAIN_ID.set(UNSPECIFIED_NETWORK.chainId, UNSPECIFIED_NETWORK) 36 | NETWORKS_BY_CHAIN_ID.set(GOERLI_NETWORK.chainId, GOERLI_NETWORK) 37 | NETWORKS_BY_CHAIN_ID.set(SEPOLIA_NETWORK.chainId, SEPOLIA_NETWORK) 38 | NETWORKS_BY_CHAIN_ID.set(GNOSIS_NETWORK.chainId, GNOSIS_NETWORK) 39 | NETWORKS_BY_CHAIN_ID.set(POLYGON_NETWORK.chainId, POLYGON_NETWORK) 40 | NETWORKS_BY_CHAIN_ID.set(MUMBAI_NETWORK.chainId, MUMBAI_NETWORK) 41 | NETWORKS_BY_CHAIN_ID.set(BINANCE_NETWORK.chainId, BINANCE_NETWORK) 42 | NETWORKS_BY_CHAIN_ID.set(BINANCE_TESTNET_NETWORK.chainId, BINANCE_TESTNET_NETWORK) 43 | NETWORKS_BY_CHAIN_ID.set(OPTIMISM_NETWORK.chainId, OPTIMISM_NETWORK) 44 | NETWORKS_BY_CHAIN_ID.set(OPTIMISM_KOVAN_NETWORK.chainId, OPTIMISM_KOVAN_NETWORK) 45 | NETWORKS_BY_CHAIN_ID.set(OPTIMISM_GOERLI_NETWORK.chainId, OPTIMISM_GOERLI_NETWORK) 46 | NETWORKS_BY_CHAIN_ID.set(ARBITRUM_NETWORK.chainId, ARBITRUM_NETWORK) 47 | NETWORKS_BY_CHAIN_ID.set(ARBITRUM_RINKEBY_NETWORK.chainId, ARBITRUM_RINKEBY_NETWORK) 48 | NETWORKS_BY_CHAIN_ID.set(ARBITRUM_GOERLI_NETWORK.chainId, ARBITRUM_GOERLI_NETWORK) 49 | NETWORKS_BY_CHAIN_ID.set(AVALANCHE_NETWORK.chainId, AVALANCHE_NETWORK) 50 | NETWORKS_BY_CHAIN_ID.set(AVALANCHE_FUJI_NETWORK.chainId, AVALANCHE_FUJI_NETWORK) 51 | NETWORKS_BY_CHAIN_ID.set(CRONOS_NETWORK.chainId, CRONOS_NETWORK) 52 | NETWORKS_BY_CHAIN_ID.set(CRONOS_TESTNET_NETWORK.chainId, CRONOS_TESTNET_NETWORK) 53 | NETWORKS_BY_CHAIN_ID.set(FANTOM_NETWORK.chainId, FANTOM_NETWORK) 54 | NETWORKS_BY_CHAIN_ID.set(FANTOM_TESTNET_NETWORK.chainId, FANTOM_TESTNET_NETWORK) 55 | NETWORKS_BY_CHAIN_ID.set(AURORA_NETWORK.chainId, AURORA_NETWORK) 56 | NETWORKS_BY_CHAIN_ID.set(AURORA_BETA_NETWORK.chainId, AURORA_BETA_NETWORK) 57 | NETWORKS_BY_CHAIN_ID.set(AURORA_TESTNET_NETWORK.chainId, AURORA_TESTNET_NETWORK) 58 | 59 | const NETWORKS_BY_NAME: Map = new Map() 60 | NETWORKS_BY_NAME.set(MAINNET_NETWORK.name, MAINNET_NETWORK) 61 | NETWORKS_BY_NAME.set(UNSPECIFIED_NETWORK.name, UNSPECIFIED_NETWORK) 62 | NETWORKS_BY_NAME.set(GOERLI_NETWORK.name, GOERLI_NETWORK) 63 | NETWORKS_BY_NAME.set(SEPOLIA_NETWORK.name, SEPOLIA_NETWORK) 64 | NETWORKS_BY_NAME.set(GNOSIS_NETWORK.name, GNOSIS_NETWORK) 65 | NETWORKS_BY_NAME.set(POLYGON_NETWORK.name, POLYGON_NETWORK) 66 | NETWORKS_BY_NAME.set(MUMBAI_NETWORK.name, MUMBAI_NETWORK) 67 | NETWORKS_BY_NAME.set(BINANCE_NETWORK.name, BINANCE_NETWORK) 68 | NETWORKS_BY_NAME.set(BINANCE_TESTNET_NETWORK.name, BINANCE_TESTNET_NETWORK) 69 | NETWORKS_BY_NAME.set(OPTIMISM_NETWORK.name, OPTIMISM_NETWORK) 70 | NETWORKS_BY_NAME.set(OPTIMISM_KOVAN_NETWORK.name, OPTIMISM_KOVAN_NETWORK) 71 | NETWORKS_BY_NAME.set(OPTIMISM_GOERLI_NETWORK.name, OPTIMISM_GOERLI_NETWORK) 72 | NETWORKS_BY_NAME.set(ARBITRUM_NETWORK.name, ARBITRUM_NETWORK) 73 | NETWORKS_BY_NAME.set(ARBITRUM_RINKEBY_NETWORK.name, ARBITRUM_RINKEBY_NETWORK) 74 | NETWORKS_BY_NAME.set(ARBITRUM_GOERLI_NETWORK.name, ARBITRUM_GOERLI_NETWORK) 75 | NETWORKS_BY_NAME.set(AVALANCHE_NETWORK.name, AVALANCHE_NETWORK) 76 | NETWORKS_BY_NAME.set(AVALANCHE_FUJI_NETWORK.name, AVALANCHE_FUJI_NETWORK) 77 | NETWORKS_BY_NAME.set(CRONOS_NETWORK.name, CRONOS_NETWORK) 78 | NETWORKS_BY_NAME.set(CRONOS_TESTNET_NETWORK.name, CRONOS_TESTNET_NETWORK) 79 | NETWORKS_BY_NAME.set(FANTOM_NETWORK.name, FANTOM_NETWORK) 80 | NETWORKS_BY_NAME.set(FANTOM_TESTNET_NETWORK.name, FANTOM_TESTNET_NETWORK) 81 | NETWORKS_BY_NAME.set(AURORA_NETWORK.name, AURORA_NETWORK) 82 | NETWORKS_BY_NAME.set(AURORA_BETA_NETWORK.name, AURORA_BETA_NETWORK) 83 | NETWORKS_BY_NAME.set(AURORA_TESTNET_NETWORK.name, AURORA_TESTNET_NETWORK) 84 | 85 | export { NETWORKS_BY_CHAIN_ID, NETWORKS_BY_NAME } 86 | -------------------------------------------------------------------------------- /src/ethers.custom-rpcs.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AbstractProvider, 3 | EtherscanProvider, 4 | FallbackProvider, 5 | FetchRequest, 6 | getDefaultProvider, 7 | JsonRpcProvider, 8 | Network, 9 | Networkish, 10 | } from 'ethers' 11 | import { 12 | BINANCE_NETWORK, 13 | BINANCE_POCKET_DEFAULT_APP_ID, 14 | BINANCE_TESTNET_NETWORK, 15 | BSCSCAN_DEFAULT_API_KEY, 16 | GOERLI_NETWORK, 17 | MAINNET_NETWORK, 18 | SEPOLIA_NETWORK, 19 | } from './ethers.constants' 20 | import { ProviderOptions } from './ethers.interface' 21 | import { getNetwork, isBinanceNetwork } from './ethers.utils' 22 | 23 | export class BscscanProvider extends EtherscanProvider { 24 | constructor(_network: Networkish, apiKey?: string) { 25 | const network = getNetwork(_network) 26 | 27 | super(network.chainId, apiKey || BSCSCAN_DEFAULT_API_KEY) 28 | } 29 | 30 | isCommunityResource(): boolean { 31 | return this.apiKey === BSCSCAN_DEFAULT_API_KEY 32 | } 33 | } 34 | 35 | export class BinancePocketProvider extends JsonRpcProvider { 36 | readonly applicationId!: string 37 | readonly applicationSecret!: null | string 38 | 39 | constructor(_network?: Networkish, applicationId?: null | string, applicationSecret?: null | string) { 40 | const network = Network.from(_network) 41 | 42 | if (applicationId == null) { 43 | applicationId = BINANCE_POCKET_DEFAULT_APP_ID 44 | } 45 | 46 | if (applicationSecret == null) { 47 | applicationSecret = null 48 | } 49 | 50 | const options = { staticNetwork: network } 51 | 52 | const request = BinancePocketProvider.getRequest(network, applicationId, applicationSecret) 53 | super(request, network, options) 54 | 55 | this.applicationId = applicationId 56 | this.applicationSecret = applicationSecret 57 | } 58 | 59 | static getHost(name: string): string { 60 | switch (name) { 61 | case BINANCE_NETWORK.name: 62 | return 'bsc-mainnet.gateway.pokt.network' 63 | case BINANCE_TESTNET_NETWORK.name: 64 | return 'bsc-testnet.gateway.pokt.network' 65 | default: 66 | throw new Error(`unsupported network ${name}`) 67 | } 68 | } 69 | 70 | _getProvider(chainId: number): AbstractProvider { 71 | try { 72 | return new BinancePocketProvider(chainId, this.applicationId, this.applicationSecret) 73 | } catch {} 74 | return super._getProvider(chainId) 75 | } 76 | 77 | static getRequest(network: Network, applicationId?: null | string, applicationSecret?: null | string): FetchRequest { 78 | if (applicationId == null) { 79 | applicationId = BINANCE_POCKET_DEFAULT_APP_ID 80 | } 81 | 82 | const request = new FetchRequest(`https:/\/${BinancePocketProvider.getHost(network.name)}/v1/lb/${applicationId}`) 83 | request.allowGzip = true 84 | 85 | if (applicationSecret) { 86 | request.setCredentials('', applicationSecret) 87 | } 88 | 89 | return request 90 | } 91 | 92 | isCommunityResource(): boolean { 93 | return this.applicationId === BINANCE_POCKET_DEFAULT_APP_ID 94 | } 95 | } 96 | 97 | export class MoralisProvider extends JsonRpcProvider { 98 | public readonly applicationId: string 99 | public readonly region: string 100 | 101 | constructor(_network?: Networkish, applicationId?: string, region?: string) { 102 | if (!_network) { 103 | _network = 'mainnet' 104 | } 105 | const network = Network.from(_network) 106 | 107 | if (!applicationId) { 108 | throw new Error('Invalid moralis apiKey') 109 | } 110 | 111 | if (!region) { 112 | region = 'nyc' 113 | } 114 | 115 | const options = { staticNetwork: network } 116 | 117 | const request = MoralisProvider.getRequest(network, applicationId, region) 118 | 119 | super(request, network, options) 120 | 121 | this.applicationId = applicationId 122 | this.region = region 123 | } 124 | 125 | _getProvider(chainId: number): AbstractProvider { 126 | try { 127 | return new MoralisProvider(chainId, this.applicationId, this.region) 128 | } catch {} 129 | return super._getProvider(chainId) 130 | } 131 | 132 | static getRequest(network: Network, applicationId: string, region: string): FetchRequest { 133 | let endpoint: string 134 | 135 | switch (network.name) { 136 | case BINANCE_NETWORK.name: 137 | endpoint = 'bsc/mainnet' 138 | break 139 | case BINANCE_TESTNET_NETWORK.name: 140 | endpoint = 'bsc/testnet' 141 | break 142 | case MAINNET_NETWORK.name: 143 | endpoint = 'eth/mainnet' 144 | break 145 | case GOERLI_NETWORK.name: 146 | endpoint = 'eth/goerli' 147 | break 148 | case SEPOLIA_NETWORK.name: 149 | endpoint = 'eth/sepolia' 150 | break 151 | default: 152 | throw new Error(`unsupported network ${network.name}`) 153 | } 154 | 155 | const request = new FetchRequest(`https://speedy-nodes-${region}.moralis.io/${applicationId}/${endpoint}`) 156 | 157 | request.allowGzip = true 158 | 159 | return request 160 | } 161 | } 162 | 163 | export async function getFallbackProvider( 164 | providers: AbstractProvider[] = [], 165 | quorum = 1, 166 | ): Promise { 167 | if (providers.length < 1) { 168 | throw new Error( 169 | 'Error in provider creation. The property "useDefaultProvider" is false and the providers supplied are invalid.', 170 | ) 171 | } 172 | 173 | if (providers.length > 1) { 174 | /** 175 | * FallbackProvider with selected providers. 176 | * @see {@link https://docs.ethers.org/v6/api/providers/fallback-provider/} 177 | */ 178 | return new FallbackProvider(providers, undefined, { quorum }) 179 | } 180 | 181 | return providers[0] 182 | } 183 | 184 | export async function getBinanceDefaultProvider( 185 | network: Network, 186 | options?: Pick, 187 | ) { 188 | const providers: Array = [ 189 | new BscscanProvider(network, options?.bscscan), 190 | new BinancePocketProvider(network, options?.pocket?.applicationId, options?.pocket?.applicationSecretKey), 191 | ] 192 | 193 | if (options?.moralis) { 194 | providers.push(new MoralisProvider(network, options?.moralis?.apiKey, options?.moralis?.region)) 195 | } 196 | 197 | return getFallbackProvider(providers, options?.quorum ?? Math.min(providers.length, 2)) 198 | } 199 | 200 | export async function getNetworkDefaultProvider(network: Network, options: ProviderOptions = {}) { 201 | if (isBinanceNetwork(network)) { 202 | return getBinanceDefaultProvider(network, options) 203 | } 204 | 205 | return getDefaultProvider(network, options) 206 | } 207 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 3.0.1 4 | Published by **[blockcoders](https://github.com/blockcoders)** on **2025/12/16** 5 | - Update peer dependency @nestjs/common to ^11.1.6 6 | 7 | ## 3.0.0 8 | Published by **[blockcoders](https://github.com/blockcoders)** on **2025/10/01** 9 | - [#ec409ec](https://github.com/blockcoders/nestjs-ethers/commit/ec409ece03da220d38ff5d0d4c39c19a795bf9cd) Use Nest.js v11 10 | - [#168](https://github.com/blockcoders/nestjs-ethers/pull/168) add support for ethers v6 by [@MMujtabaRoohani](https://github.com/MMujtabaRoohani) 11 | 12 | ## 2.2.0 13 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/10/17** 14 | - [#154](https://github.com/blockcoders/nestjs-ethers/pull/154) Update nestjs to 10.x 15 | - [#160](https://github.com/blockcoders/nestjs-ethers/pull/160) fixes 16 | - [#155](https://github.com/blockcoders/nestjs-ethers/pull/155) Remove jest in order to use tap 17 | 18 | ## 2.1.0 19 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/10/17** 20 | - [#148](https://github.com/blockcoders/nestjs-ethers/pull/148) Added option to use MulticallProvider instead of StaticJsonRpcProvider when using custom provider by [@0x67](https://github.com/0x67) 21 | 22 | ## 2.0.3 23 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/01/07** 24 | - Add @ethersproject/* as dependencies 25 | 26 | ## 2.0.2 27 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/01/07** 28 | - Update Readme 29 | 30 | ## 2.0.1 31 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/01/07** 32 | - [#145](https://github.com/blockcoders/nestjs-ethers/pull/145) Fix @nestjs/common peer dependenciy version 33 | 34 | ## 2.0.0 35 | Published by **[blockcoders](https://github.com/blockcoders)** on **2023/01/07** 36 | - [#140](https://github.com/blockcoders/nestjs-ethers/pull/140) Release v2.0.0 - Nest.js v9 37 | - [#142](https://github.com/blockcoders/nestjs-ethers/pull/142) Update README.md by [@copocaneta](https://github.com/copocaneta) 38 | 39 | ### BREAKING CHANGE 40 | - Dropped support for node < 14 41 | - Upgrade @nestjs/* from 8.x to 9.x 42 | - Remove deprecated ethereum chains (ropsten, rinkeby and kovan). 43 | - Add new RPC providers Moralis and Ankr. 44 | - Ethers.js is not longer part of the index.ts export. 45 | - @ethersproject/* is now part of peerDependencies. 46 | - Rename `MATIC_NETWORK` with `POLYGON_NETWORK`. 47 | 48 | ## 1.0.3 49 | Published by **[blockcoders](https://github.com/blockcoders)** on **2022/05/08** 50 | - [#141](https://github.com/blockcoders/nestjs-ethers/pull/141) Update dependencies 51 | - [#139](https://github.com/blockcoders/nestjs-ethers/pull/139) Fix: Function name createWalletFromEncryptedJson by [@GustavoRSSilva](https://github.com/GustavoRSSilva) 52 | - [#138](https://github.com/blockcoders/nestjs-ethers/pull/138) Fix: README injected variable ethersContract by [@GustavoRSSilva](https://github.com/GustavoRSSilva) 53 | 54 | ## 1.0.2 55 | Published by **[blockcoders](https://github.com/blockcoders)** on **2022/05/08** 56 | - [#137](https://github.com/blockcoders/nestjs-ethers/pull/137) Update dependencies 57 | - [#135](https://github.com/blockcoders/nestjs-ethers/pull/135) Fix typo getSigneroken to getSignerToken by [@hanchchch](https://github.com/hanchchch) 58 | 59 | ## 1.0.1 60 | Published by **[blockcoders](https://github.com/blockcoders)** on **2022/01/15** 61 | - [#133](https://github.com/blockcoders/nestjs-ethers/pull/133) Update dependencies 62 | 63 | ## 1.0.0 64 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/09/16** 65 | - [#129](https://github.com/blockcoders/nestjs-ethers/pull/129) Add module context token 66 | - [#128](https://github.com/blockcoders/nestjs-ethers/pull/128) Add option waitUntilIsConnected 67 | - [#127](https://github.com/blockcoders/nestjs-ethers/pull/127) Custom StaticJsonRpcProvider 68 | - [#126](https://github.com/blockcoders/nestjs-ethers/pull/126) BscScan Provider 69 | - [#125](https://github.com/blockcoders/nestjs-ethers/pull/125) Add precommit 70 | - [#124](https://github.com/blockcoders/nestjs-ethers/pull/124) Add new network chains 71 | - [#123](https://github.com/blockcoders/nestjs-ethers/pull/123) Export everything in ethers module 72 | - [#122](https://github.com/blockcoders/nestjs-ethers/pull/122) Update ethers to 5.4.6 73 | - [#119](https://github.com/blockcoders/nestjs-ethers/pull/119) Remove dependabot.yml 74 | - [#118](https://github.com/blockcoders/nestjs-ethers/pull/118) Update eslint 75 | 76 | ### BREAKING CHANGE 77 | - Replace `EthersBaseProvider` with ethers `BaseProvider` interface. 78 | - Replace `SmartContractInterface` with ethers `ContractInterface` interface. 79 | - Replace `WalletSigner` with ethers `Wallet` interface. 80 | - Replace `SmartContractFactory` with ethers `ContractFactory` interface. 81 | - `RandomWalletSignerOptions` was renamed to `RandomWalletOptions` 82 | - `EthersSigner` and `EthersContract` are not longer part of the global export. Now these two provider are injected in `forRoot` and `forRootAsync`. 83 | - `@InjectContractProvider` decorator declares the `EthersContract` class as a class that can be managed by the Nest IoC container. 84 | - `@InjectSignerProvider` decorator declares the `EthersSigner` class as a class that can be managed by the Nest IoC . 85 | 86 | ## 0.3.2 87 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/08/12** 88 | - [#111](https://github.com/blockcoders/nestjs-ethers/pull/111) Update dependencies 89 | - [#110](https://github.com/blockcoders/nestjs-ethers/pull/110) Remove Dependabot Badge 90 | 91 | ## 0.3.1 92 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/07/13** 93 | - [#93](https://github.com/blockcoders/nestjs-ethers/pull/93) Update dependencies 94 | 95 | ## 0.3.0 96 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/04/21** 97 | - [#19](https://github.com/blockcoders/nestjs-ethers/pull/19) Release v0.3.0 - EthersContract implementation 98 | - [#18](https://github.com/blockcoders/nestjs-ethers/pull/18) Add EthersContract to the README 99 | - [#17](https://github.com/blockcoders/nestjs-ethers/pull/17) Add SmartContract creation 100 | 101 | ## 0.2.0 102 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/04/17** 103 | - [#16](https://github.com/blockcoders/nestjs-ethers/pull/16) Release v0.2.0 - EthersSigner implementation 104 | - [#15](https://github.com/blockcoders/nestjs-ethers/pull/15) Update Readme with EthersSigner 105 | - [#14](https://github.com/blockcoders/nestjs-ethers/pull/14) Update PULL_REQUEST_TEMPLATE 106 | - [#13](https://github.com/blockcoders/nestjs-ethers/pull/13) Add wallet signer service 107 | 108 | ### BREAKING CHANGE 109 | - Removed `providerName` option from `forRoot` and `forRootAsync` functions. 110 | 111 | ## 0.1.0 112 | Published by **[blockcoders](https://github.com/blockcoders)** on **2021/04/14** 113 | - [#10](https://github.com/blockcoders/nestjs-ethers/pull/10) Release v0.1.0 - Ethereum Module implementation for NestJS based on [Ethers.js](https://github.com/ethers-io/ethers.js/) 114 | -------------------------------------------------------------------------------- /test/ethers.contract.spec.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Injectable, Module } from '@nestjs/common' 2 | import { Contract } from 'ethers' 3 | import * as nock from 'nock' 4 | import t from 'tap' 5 | import { EthersContract, EthersModule, EthersSigner, InjectContractProvider, InjectSignerProvider } from '../src' 6 | import * as ABI from './utils/ABI.json' 7 | import { appRequest } from './utils/appRequest' 8 | import { ETHERS_ADDRESS, ETHERS_PRIVATE_KEY } from './utils/constants' 9 | import { nockAllRPCRequests } from './utils/mockResponses' 10 | import { platforms } from './utils/platforms' 11 | 12 | t.test('EthersContract', (t) => { 13 | t.beforeEach(() => { 14 | nock.cleanAll() 15 | nockAllRPCRequests() 16 | }) 17 | 18 | t.before(() => { 19 | if (!nock.isActive()) { 20 | nock.activate() 21 | } 22 | 23 | nock.disableNetConnect() 24 | nock.enableNetConnect('127.0.0.1') 25 | }) 26 | 27 | t.after(() => nock.restore()) 28 | 29 | for (const PlatformAdapter of platforms) { 30 | t.test(PlatformAdapter.name, (t) => { 31 | t.test('forRoot', (t) => { 32 | t.test( 33 | 'should create an instance of the SmartContract attached to an address with a provider injected', 34 | async (t) => { 35 | @Injectable() 36 | class TestService { 37 | constructor( 38 | @InjectContractProvider() 39 | private readonly contract: EthersContract, 40 | ) {} 41 | async someMethod(): Promise { 42 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 43 | 44 | if (!(await contract?.runner?.provider?.getNetwork())) { 45 | throw new Error('No provider injected') 46 | } 47 | 48 | return contract.getAddress() 49 | } 50 | } 51 | 52 | @Controller('/') 53 | class TestController { 54 | constructor(private readonly service: TestService) {} 55 | @Get() 56 | async get() { 57 | const address = await this.service.someMethod() 58 | 59 | return { address: address.toLowerCase() } 60 | } 61 | } 62 | 63 | @Module({ 64 | imports: [EthersModule.forRoot()], 65 | controllers: [TestController], 66 | providers: [TestService], 67 | }) 68 | class TestModule {} 69 | 70 | const res = await appRequest(t, TestModule, PlatformAdapter) 71 | 72 | t.equal(res.statusCode, 200) 73 | t.same(res.body, { address: ETHERS_ADDRESS }) 74 | t.end() 75 | }, 76 | ) 77 | 78 | t.test('should be able to set a Wallet into a SmartContract', async (t) => { 79 | @Injectable() 80 | class TestService { 81 | constructor( 82 | @InjectContractProvider() 83 | private readonly contract: EthersContract, 84 | @InjectSignerProvider() 85 | private readonly signer: EthersSigner, 86 | ) {} 87 | async someMethod(): Promise { 88 | const wallet = this.signer.createWallet(ETHERS_PRIVATE_KEY) 89 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI, wallet) 90 | 91 | if (!(await contract?.runner?.provider?.getNetwork())) { 92 | throw new Error('No provider injected') 93 | } 94 | 95 | return contract.getAddress() 96 | } 97 | } 98 | 99 | @Controller('/') 100 | class TestController { 101 | constructor(private readonly service: TestService) {} 102 | @Get() 103 | async get() { 104 | const address = await this.service.someMethod() 105 | 106 | return { address: address.toLowerCase() } 107 | } 108 | } 109 | 110 | @Module({ 111 | imports: [EthersModule.forRoot()], 112 | controllers: [TestController], 113 | providers: [TestService], 114 | }) 115 | class TestModule {} 116 | 117 | const res = await appRequest(t, TestModule, PlatformAdapter) 118 | 119 | t.equal(res.statusCode, 200) 120 | t.same(res.body, { address: ETHERS_ADDRESS }) 121 | t.end() 122 | }) 123 | 124 | t.end() 125 | }) 126 | 127 | t.test('forRootAsync', (t) => { 128 | t.test( 129 | 'should create an instance of the SmartContract attached to an address with a provider injected', 130 | async (t) => { 131 | @Injectable() 132 | class TestService { 133 | constructor( 134 | @InjectContractProvider() 135 | private readonly contract: EthersContract, 136 | ) {} 137 | async someMethod(): Promise { 138 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 139 | 140 | if (!(await contract?.runner?.provider?.getNetwork())) { 141 | throw new Error('No provider injected') 142 | } 143 | 144 | return contract.getAddress() 145 | } 146 | } 147 | 148 | @Controller('/') 149 | class TestController { 150 | constructor(private readonly service: TestService) {} 151 | @Get() 152 | async get() { 153 | const address = await this.service.someMethod() 154 | 155 | return { address: address.toLowerCase() } 156 | } 157 | } 158 | 159 | @Module({ 160 | imports: [ 161 | EthersModule.forRootAsync({ 162 | useFactory: () => { 163 | return { 164 | useDefaultProvider: true, 165 | } 166 | }, 167 | }), 168 | ], 169 | controllers: [TestController], 170 | providers: [TestService], 171 | }) 172 | class TestModule {} 173 | 174 | const res = await appRequest(t, TestModule, PlatformAdapter) 175 | 176 | t.equal(res.statusCode, 200) 177 | t.same(res.body, { address: ETHERS_ADDRESS }) 178 | t.end() 179 | }, 180 | ) 181 | 182 | t.test('should be able to set a Wallet into a SmartContract', async (t) => { 183 | @Injectable() 184 | class TestService { 185 | constructor( 186 | @InjectContractProvider() 187 | private readonly contract: EthersContract, 188 | @InjectSignerProvider() 189 | private readonly signer: EthersSigner, 190 | ) {} 191 | async someMethod(): Promise { 192 | const wallet = this.signer.createWallet(ETHERS_PRIVATE_KEY) 193 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI, wallet) 194 | 195 | if (!(await contract?.runner?.provider?.getNetwork())) { 196 | throw new Error('No provider injected') 197 | } 198 | 199 | return contract.getAddress() 200 | } 201 | } 202 | 203 | @Controller('/') 204 | class TestController { 205 | constructor(private readonly service: TestService) {} 206 | @Get() 207 | async get() { 208 | const address = await this.service.someMethod() 209 | 210 | return { address: address.toLowerCase() } 211 | } 212 | } 213 | 214 | @Module({ 215 | imports: [ 216 | EthersModule.forRootAsync({ 217 | useFactory: () => { 218 | return { 219 | useDefaultProvider: true, 220 | } 221 | }, 222 | }), 223 | ], 224 | controllers: [TestController], 225 | providers: [TestService], 226 | }) 227 | class TestModule {} 228 | 229 | const res = await appRequest(t, TestModule, PlatformAdapter) 230 | 231 | t.equal(res.statusCode, 200) 232 | t.same(res.body, { address: ETHERS_ADDRESS }) 233 | t.end() 234 | }) 235 | 236 | t.end() 237 | }) 238 | 239 | t.end() 240 | }) 241 | } 242 | 243 | t.end() 244 | }) 245 | -------------------------------------------------------------------------------- /test/ethers.custom-rpcs.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AlchemyProvider, 3 | CloudflareProvider, 4 | EtherscanProvider, 5 | FallbackProvider, 6 | InfuraProvider, 7 | QuickNodeProvider, 8 | } from 'ethers' 9 | import * as nock from 'nock' 10 | import t from 'tap' 11 | import { 12 | ARBITRUM_NETWORK, 13 | BINANCE_NETWORK, 14 | BINANCE_POCKET_DEFAULT_APP_ID, 15 | BINANCE_TESTNET_NETWORK, 16 | GOERLI_NETWORK, 17 | MAINNET_NETWORK, 18 | SEPOLIA_NETWORK, 19 | } from '../src/ethers.constants' 20 | import { 21 | BinancePocketProvider, 22 | BscscanProvider, 23 | getBinanceDefaultProvider, 24 | getFallbackProvider, 25 | getNetworkDefaultProvider, 26 | MoralisProvider, 27 | } from '../src/ethers.custom-rpcs' 28 | 29 | t.test('Ethers Custom RPC', (t) => { 30 | t.beforeEach(() => nock.cleanAll()) 31 | 32 | t.before(() => { 33 | if (!nock.isActive()) { 34 | nock.activate() 35 | } 36 | 37 | nock.disableNetConnect() 38 | nock.enableNetConnect('127.0.0.1') 39 | }) 40 | 41 | t.after(() => nock.restore()) 42 | 43 | t.test('BscscanProvider', (t) => { 44 | t.test('isCommunityResource', (t) => { 45 | t.test('should return a bsc communt.testy resource', (t) => { 46 | const provider = new BscscanProvider(BINANCE_NETWORK) 47 | 48 | t.ok(provider.isCommunityResource()) 49 | t.end() 50 | }) 51 | 52 | t.test('should return a not bsc communt.testy resource', (t) => { 53 | const provider = new BscscanProvider(BINANCE_NETWORK, '1234') 54 | 55 | t.notOk(provider.isCommunityResource()) 56 | t.end() 57 | }) 58 | 59 | t.end() 60 | }) 61 | 62 | t.end() 63 | }) 64 | 65 | t.test('BinancePocketProvider', (t) => { 66 | t.test('getRequest', (t) => { 67 | t.test('should return a bsc network url', (t) => { 68 | const provider = new BinancePocketProvider(BINANCE_NETWORK.name) 69 | 70 | t.equal( 71 | provider._getConnection().url, 72 | 'https://bsc-mainnet.gateway.pokt.network/v1/lb/6136201a7bad1500343e248d', 73 | ) 74 | t.end() 75 | }) 76 | 77 | t.test('should return a bsc testnet network url', (t) => { 78 | const provider = new BinancePocketProvider(BINANCE_TESTNET_NETWORK.name) 79 | 80 | t.equal( 81 | provider._getConnection().url, 82 | 'https://bsc-testnet.gateway.pokt.network/v1/lb/6136201a7bad1500343e248d', 83 | ) 84 | t.end() 85 | }) 86 | 87 | t.test('should throw an error if the network is not valid', (t) => { 88 | t.throws(() => new BinancePocketProvider(1)) 89 | t.end() 90 | }) 91 | 92 | t.test('should use an applicationSecretKey', (t) => { 93 | const provider = new BinancePocketProvider(BINANCE_TESTNET_NETWORK.name, '1234', '4321') 94 | const credentials = provider._getConnection().credentials 95 | 96 | t.equal(provider._getConnection().url, 'https://bsc-testnet.gateway.pokt.network/v1/lb/1234') 97 | t.equal(credentials, ':4321') 98 | t.end() 99 | }) 100 | 101 | t.test('should handle null applicationId in getRequest', (t) => { 102 | const request = BinancePocketProvider.getRequest(BINANCE_NETWORK, null, null) 103 | 104 | t.equal( 105 | request.url, 106 | `https://${BinancePocketProvider.getHost(BINANCE_NETWORK.name)}/v1/lb/${BINANCE_POCKET_DEFAULT_APP_ID}`, 107 | ) 108 | t.end() 109 | }) 110 | 111 | t.end() 112 | }) 113 | 114 | t.test('_getProvider', (t) => { 115 | t.test('should return new BinancePocketProvider for valid chainId', (t) => { 116 | const provider = new BinancePocketProvider(BINANCE_NETWORK.name, '1234') 117 | const newProvider = provider._getProvider(Number(BINANCE_NETWORK.chainId)) 118 | 119 | t.type(newProvider, BinancePocketProvider) 120 | t.end() 121 | }) 122 | 123 | t.test('should fallback to super._getProvider for any unsupported network', (t) => { 124 | const provider = new BinancePocketProvider(BINANCE_NETWORK.name, '1234') 125 | t.throws(() => provider._getProvider(Number(MAINNET_NETWORK.chainId))) 126 | t.end() 127 | }) 128 | 129 | t.end() 130 | }) 131 | 132 | t.test('isCommunityResource', (t) => { 133 | t.test('should return a bsc communt.testy resource', (t) => { 134 | const provider = new BinancePocketProvider(BINANCE_NETWORK) 135 | 136 | t.ok(provider.isCommunityResource()) 137 | t.end() 138 | }) 139 | 140 | t.test('should return a not bsc communt.testy resource', (t) => { 141 | const provider = new BinancePocketProvider(BINANCE_NETWORK, '1234') 142 | 143 | t.notOk(provider.isCommunityResource()) 144 | t.end() 145 | }) 146 | 147 | t.end() 148 | }) 149 | 150 | t.end() 151 | }) 152 | 153 | t.test('MoralisProvider', (t) => { 154 | t.test('getRequest', (t) => { 155 | t.test('should return the connection info', (t) => { 156 | const provider = new MoralisProvider(BINANCE_NETWORK, '1234', 'caba') 157 | 158 | t.equal(provider._getConnection().url, 'https://speedy-nodes-caba.moralis.io/1234/bsc/mainnet') 159 | t.end() 160 | }) 161 | 162 | t.test('should return a bsc network url', (t) => { 163 | const provider = new MoralisProvider(BINANCE_NETWORK, '1234') 164 | 165 | t.equal(provider._getConnection().url, 'https://speedy-nodes-nyc.moralis.io/1234/bsc/mainnet') 166 | t.end() 167 | }) 168 | 169 | t.test('should return a bsc testnet network url', (t) => { 170 | const provider = new MoralisProvider(BINANCE_TESTNET_NETWORK, '1234') 171 | 172 | t.equal(provider._getConnection().url, 'https://speedy-nodes-nyc.moralis.io/1234/bsc/testnet') 173 | t.end() 174 | }) 175 | 176 | t.test('should return a mainnet network url', (t) => { 177 | const provider = new MoralisProvider(MAINNET_NETWORK, '1234') 178 | 179 | t.equal(provider._getConnection().url, 'https://speedy-nodes-nyc.moralis.io/1234/eth/mainnet') 180 | t.end() 181 | }) 182 | 183 | t.test('should return a goerli network url', (t) => { 184 | const provider = new MoralisProvider(GOERLI_NETWORK, '1234') 185 | 186 | t.equal(provider._getConnection().url, 'https://speedy-nodes-nyc.moralis.io/1234/eth/goerli') 187 | t.end() 188 | }) 189 | 190 | t.test('should return a sepolia network url', (t) => { 191 | const provider = new MoralisProvider(SEPOLIA_NETWORK, '1234') 192 | 193 | t.equal(provider._getConnection().url, 'https://speedy-nodes-nyc.moralis.io/1234/eth/sepolia') 194 | t.end() 195 | }) 196 | 197 | t.test('should throw an error if the network is not valid', (t) => { 198 | t.throws(() => new MoralisProvider(69, '1234')) 199 | t.end() 200 | }) 201 | 202 | t.test('should use mainnet network when none provided', (t) => { 203 | const provider = new MoralisProvider(undefined, '1234') 204 | 205 | t.equal(provider._network.chainId, MAINNET_NETWORK.chainId) 206 | t.end() 207 | }) 208 | 209 | t.test('should throw error when no apiKey provided', (t) => { 210 | t.throws(() => new MoralisProvider(BINANCE_NETWORK, undefined), 'Invalid moralis apiKey') 211 | t.end() 212 | }) 213 | 214 | t.end() 215 | }) 216 | 217 | t.test('_getProvider', (t) => { 218 | t.test('should return new MoralisProvider for valid chainId', (t) => { 219 | const provider = new MoralisProvider(BINANCE_NETWORK, '1234') 220 | const newProvider = provider._getProvider(Number(BINANCE_NETWORK.chainId)) 221 | 222 | t.type(newProvider, MoralisProvider) 223 | t.end() 224 | }) 225 | 226 | t.test('should fallback to super._getProvider for any unsupported network', (t) => { 227 | const provider = new MoralisProvider(BINANCE_NETWORK, '1234') 228 | t.throws(() => provider._getProvider(Number(ARBITRUM_NETWORK.chainId))) 229 | t.end() 230 | }) 231 | 232 | t.end() 233 | }) 234 | 235 | t.end() 236 | }) 237 | 238 | t.test('getFallbackProvider', (t) => { 239 | t.test('should throw an error if the providers are empty', (t) => { 240 | t.rejects(() => getFallbackProvider()) 241 | t.end() 242 | }) 243 | 244 | t.test('should return a instance of CloudflareProvider', async (t) => { 245 | const provider = await getFallbackProvider([new CloudflareProvider(MAINNET_NETWORK)], undefined) 246 | 247 | t.type(provider, CloudflareProvider) 248 | t.end() 249 | }) 250 | 251 | t.test('should return a instance of FallbackProvider', async (t) => { 252 | const provider = await getFallbackProvider( 253 | [new CloudflareProvider(MAINNET_NETWORK), new InfuraProvider(MAINNET_NETWORK)], 254 | undefined, 255 | ) 256 | 257 | t.type(provider, FallbackProvider) 258 | t.end() 259 | }) 260 | 261 | t.end() 262 | }) 263 | 264 | t.test('getBinanceDefaultProvider', (t) => { 265 | t.test('should return a instance of FallbackProvider with BscscanProvider and BinancePocketProvider', async (t) => { 266 | const provider = await getBinanceDefaultProvider(BINANCE_TESTNET_NETWORK, { quorum: 1 }) 267 | 268 | t.type(provider, FallbackProvider) 269 | t.type((provider as FallbackProvider).providerConfigs[0].provider, BscscanProvider) 270 | t.type((provider as FallbackProvider).providerConfigs[1].provider, BinancePocketProvider) 271 | t.equal((provider as FallbackProvider).quorum, 1) 272 | t.end() 273 | }) 274 | 275 | t.test('should return a instance of FallbackProvider with BinanceMoralisProvider', async (t) => { 276 | const provider = await getBinanceDefaultProvider(BINANCE_TESTNET_NETWORK, { 277 | quorum: 2, 278 | moralis: { apiKey: '1234' }, 279 | }) 280 | 281 | t.type(provider, FallbackProvider) 282 | t.type((provider as FallbackProvider).providerConfigs[0].provider, BscscanProvider) 283 | t.type((provider as FallbackProvider).providerConfigs[1].provider, BinancePocketProvider) 284 | t.type((provider as FallbackProvider).providerConfigs[2].provider, MoralisProvider) 285 | t.equal((provider as FallbackProvider).quorum, 2) 286 | t.end() 287 | }) 288 | 289 | t.end() 290 | }) 291 | 292 | t.test('getNetworkDefaultProvider', (t) => { 293 | t.test('should return a instance of FallbackProvider with BscscanProvider and BinancePocketProvider', async (t) => { 294 | const provider = await getNetworkDefaultProvider(BINANCE_TESTNET_NETWORK, { quorum: 1 }) 295 | 296 | t.type(provider, FallbackProvider) 297 | t.type((provider as FallbackProvider).providerConfigs[0].provider, BscscanProvider) 298 | t.type((provider as FallbackProvider).providerConfigs[1].provider, BinancePocketProvider) 299 | t.equal((provider as FallbackProvider).quorum, 1) 300 | t.end() 301 | }) 302 | 303 | t.test('should return a instance of FallbackProvider with BscscanProvider and BinancePocketProvider', async (t) => { 304 | const provider = await getNetworkDefaultProvider(GOERLI_NETWORK, { quorum: 1 }) 305 | 306 | t.type(provider, FallbackProvider) 307 | t.type((provider as FallbackProvider).providerConfigs[0].provider, AlchemyProvider) 308 | t.type((provider as FallbackProvider).providerConfigs[1].provider, EtherscanProvider) 309 | t.type((provider as FallbackProvider).providerConfigs[2].provider, InfuraProvider) 310 | t.type((provider as FallbackProvider).providerConfigs[3].provider, QuickNodeProvider) 311 | t.equal((provider as FallbackProvider).quorum, 1) 312 | t.end() 313 | }) 314 | 315 | t.end() 316 | }) 317 | 318 | t.end() 319 | }) 320 | -------------------------------------------------------------------------------- /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 2021 Jose Ramirez 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 | -------------------------------------------------------------------------------- /test/ethers.signer.spec.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Injectable, Module } from '@nestjs/common' 2 | import { Mnemonic } from 'ethers' 3 | import * as nock from 'nock' 4 | import t from 'tap' 5 | import { EthersModule, EthersSigner, InjectSignerProvider } from '../src' 6 | import { appRequest } from './utils/appRequest' 7 | import { 8 | ETHERS_ADDRESS, 9 | ETHERS_JSON_WALLET, 10 | ETHERS_JSON_WALLET_PASSWORD, 11 | ETHERS_MNEMONIC, 12 | ETHERS_PRIVATE_KEY, 13 | } from './utils/constants' 14 | import { nockAllRPCRequests } from './utils/mockResponses' 15 | import { platforms } from './utils/platforms' 16 | 17 | t.test('EthersSigner', (t) => { 18 | t.beforeEach(() => { 19 | nock.cleanAll() 20 | nockAllRPCRequests() 21 | }) 22 | 23 | t.before(() => { 24 | if (!nock.isActive()) { 25 | nock.activate() 26 | } 27 | 28 | nock.disableNetConnect() 29 | nock.enableNetConnect('127.0.0.1') 30 | }) 31 | 32 | t.after(() => nock.restore()) 33 | 34 | for (const PlatformAdapter of platforms) { 35 | t.test(PlatformAdapter.name, (t) => { 36 | t.test('forRoot', (t) => { 37 | t.test('should create a wallet from a private key with a provider injected', async (t) => { 38 | @Injectable() 39 | class TestService { 40 | constructor( 41 | @InjectSignerProvider() 42 | private readonly signer: EthersSigner, 43 | ) {} 44 | async someMethod(): Promise { 45 | const wallet = this.signer.createWallet(ETHERS_PRIVATE_KEY) 46 | 47 | if (!(await wallet?.provider?.getNetwork())) { 48 | throw new Error('No provider injected') 49 | } 50 | 51 | return wallet.getAddress() 52 | } 53 | } 54 | 55 | @Controller('/') 56 | class TestController { 57 | constructor(private readonly service: TestService) {} 58 | @Get() 59 | async get() { 60 | const address = await this.service.someMethod() 61 | 62 | return { address: address.toLowerCase() } 63 | } 64 | } 65 | 66 | @Module({ 67 | imports: [EthersModule.forRoot()], 68 | controllers: [TestController], 69 | providers: [TestService], 70 | }) 71 | class TestModule {} 72 | 73 | const res = await appRequest(t, TestModule, PlatformAdapter) 74 | 75 | t.equal(res.statusCode, 200) 76 | t.same(res.body, { address: ETHERS_ADDRESS }) 77 | t.end() 78 | }) 79 | 80 | t.test('should create a random wallet With a provider injected', async (t) => { 81 | @Injectable() 82 | class TestService { 83 | constructor( 84 | @InjectSignerProvider() 85 | private readonly signer: EthersSigner, 86 | ) {} 87 | async someMethod(): Promise { 88 | const wallet = this.signer.createRandomWallet() 89 | 90 | if (!(await wallet?.provider?.getNetwork())) { 91 | throw new Error('No provider injected') 92 | } 93 | 94 | return wallet.getAddress() 95 | } 96 | } 97 | 98 | @Controller('/') 99 | class TestController { 100 | constructor(private readonly service: TestService) {} 101 | @Get() 102 | async get() { 103 | const address = await this.service.someMethod() 104 | 105 | return { address } 106 | } 107 | } 108 | 109 | @Module({ 110 | imports: [EthersModule.forRoot()], 111 | controllers: [TestController], 112 | providers: [TestService], 113 | }) 114 | class TestModule {} 115 | 116 | const res = await appRequest(t, TestModule, PlatformAdapter) 117 | 118 | t.equal(res.statusCode, 200) 119 | t.notHas(res.body, 'address') 120 | t.end() 121 | }) 122 | 123 | t.test('should create a wallet from an encrypted JSON with a provider injected', async (t) => { 124 | @Injectable() 125 | class TestService { 126 | constructor( 127 | @InjectSignerProvider() 128 | private readonly signer: EthersSigner, 129 | ) {} 130 | async someMethod(): Promise { 131 | const wallet = await this.signer.createWalletFromEncryptedJson( 132 | ETHERS_JSON_WALLET, 133 | ETHERS_JSON_WALLET_PASSWORD, 134 | ) 135 | 136 | if (!(await wallet?.provider?.getNetwork())) { 137 | throw new Error('No provider injected') 138 | } 139 | 140 | return wallet.getAddress() 141 | } 142 | } 143 | 144 | @Controller('/') 145 | class TestController { 146 | constructor(private readonly service: TestService) {} 147 | @Get() 148 | async get() { 149 | const address = await this.service.someMethod() 150 | 151 | return { address: address.toLowerCase() } 152 | } 153 | } 154 | 155 | @Module({ 156 | imports: [EthersModule.forRoot()], 157 | controllers: [TestController], 158 | providers: [TestService], 159 | }) 160 | class TestModule {} 161 | 162 | const res = await appRequest(t, TestModule, PlatformAdapter) 163 | 164 | t.equal(res.statusCode, 200) 165 | t.same(res.body, { address: ETHERS_ADDRESS }) 166 | t.end() 167 | }) 168 | 169 | t.test('should create a wallet from a mnemonic with a provider injected', async (t) => { 170 | @Injectable() 171 | class TestService { 172 | constructor( 173 | @InjectSignerProvider() 174 | private readonly signer: EthersSigner, 175 | ) {} 176 | async someMethod(): Promise { 177 | const wallet = this.signer.createWalletfromMnemonic(Mnemonic.fromPhrase(ETHERS_MNEMONIC)) 178 | 179 | if (!(await wallet?.provider?.getNetwork())) { 180 | throw new Error('No provider injected') 181 | } 182 | 183 | return wallet.getAddress() 184 | } 185 | } 186 | 187 | @Controller('/') 188 | class TestController { 189 | constructor(private readonly service: TestService) {} 190 | @Get() 191 | async get() { 192 | const address = await this.service.someMethod() 193 | 194 | return { address: address.toLowerCase() } 195 | } 196 | } 197 | 198 | @Module({ 199 | imports: [EthersModule.forRoot()], 200 | controllers: [TestController], 201 | providers: [TestService], 202 | }) 203 | class TestModule {} 204 | 205 | const res = await appRequest(t, TestModule, PlatformAdapter) 206 | 207 | t.equal(res.statusCode, 200) 208 | t.same(res.body, { address: ETHERS_ADDRESS }) 209 | t.end() 210 | }) 211 | 212 | t.test('should create a void signer from an address with a provider injected', async (t) => { 213 | @Injectable() 214 | class TestService { 215 | constructor( 216 | @InjectSignerProvider() 217 | private readonly signer: EthersSigner, 218 | ) {} 219 | async someMethod(): Promise { 220 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 221 | 222 | if (!(await wallet?.provider?.getNetwork())) { 223 | throw new Error('No provider injected') 224 | } 225 | 226 | return wallet.getAddress() 227 | } 228 | } 229 | 230 | @Controller('/') 231 | class TestController { 232 | constructor(private readonly service: TestService) {} 233 | @Get() 234 | async get() { 235 | const address = await this.service.someMethod() 236 | 237 | return { address: address.toLowerCase() } 238 | } 239 | } 240 | 241 | @Module({ 242 | imports: [EthersModule.forRoot()], 243 | controllers: [TestController], 244 | providers: [TestService], 245 | }) 246 | class TestModule {} 247 | 248 | const res = await appRequest(t, TestModule, PlatformAdapter) 249 | 250 | t.equal(res.statusCode, 200) 251 | t.same(res.body, { address: ETHERS_ADDRESS }) 252 | t.end() 253 | }) 254 | 255 | t.end() 256 | }) 257 | 258 | t.test('forRootAsync', (t) => { 259 | t.test('should create a wallet from a private key with a provider injected', async (t) => { 260 | @Injectable() 261 | class TestService { 262 | constructor( 263 | @InjectSignerProvider() 264 | private readonly signer: EthersSigner, 265 | ) {} 266 | async someMethod(): Promise { 267 | const wallet = this.signer.createWallet(ETHERS_PRIVATE_KEY) 268 | 269 | if (!(await wallet?.provider?.getNetwork())) { 270 | throw new Error('No provider injected') 271 | } 272 | 273 | return wallet.getAddress() 274 | } 275 | } 276 | 277 | @Controller('/') 278 | class TestController { 279 | constructor(private readonly service: TestService) {} 280 | @Get() 281 | async get() { 282 | const address = await this.service.someMethod() 283 | 284 | return { address: address.toLowerCase() } 285 | } 286 | } 287 | 288 | @Module({ 289 | imports: [ 290 | EthersModule.forRootAsync({ 291 | useFactory: () => { 292 | return { 293 | useDefaultProvider: true, 294 | } 295 | }, 296 | }), 297 | ], 298 | controllers: [TestController], 299 | providers: [TestService], 300 | }) 301 | class TestModule {} 302 | 303 | const res = await appRequest(t, TestModule, PlatformAdapter) 304 | 305 | t.equal(res.statusCode, 200) 306 | t.same(res.body, { address: ETHERS_ADDRESS }) 307 | t.end() 308 | }) 309 | 310 | t.test('should create a random wallet With a provider injected', async (t) => { 311 | @Injectable() 312 | class TestService { 313 | constructor( 314 | @InjectSignerProvider() 315 | private readonly signer: EthersSigner, 316 | ) {} 317 | async someMethod(): Promise { 318 | const wallet = this.signer.createRandomWallet() 319 | 320 | if (!(await wallet?.provider?.getNetwork())) { 321 | throw new Error('No provider injected') 322 | } 323 | 324 | return wallet.getAddress() 325 | } 326 | } 327 | 328 | @Controller('/') 329 | class TestController { 330 | constructor(private readonly service: TestService) {} 331 | @Get() 332 | async get() { 333 | const address = await this.service.someMethod() 334 | 335 | return { address } 336 | } 337 | } 338 | 339 | @Module({ 340 | imports: [ 341 | EthersModule.forRootAsync({ 342 | useFactory: () => { 343 | return { 344 | useDefaultProvider: true, 345 | } 346 | }, 347 | }), 348 | ], 349 | controllers: [TestController], 350 | providers: [TestService], 351 | }) 352 | class TestModule {} 353 | 354 | const res = await appRequest(t, TestModule, PlatformAdapter) 355 | 356 | t.equal(res.statusCode, 200) 357 | t.notHas(res.body, 'address') 358 | t.end() 359 | }) 360 | 361 | t.test('should create a wallet from an encrypted JSON with a provider injected', async (t) => { 362 | @Injectable() 363 | class TestService { 364 | constructor( 365 | @InjectSignerProvider() 366 | private readonly signer: EthersSigner, 367 | ) {} 368 | async someMethod(): Promise { 369 | const wallet = await this.signer.createWalletFromEncryptedJson( 370 | ETHERS_JSON_WALLET, 371 | ETHERS_JSON_WALLET_PASSWORD, 372 | ) 373 | 374 | if (!(await wallet?.provider?.getNetwork())) { 375 | throw new Error('No provider injected') 376 | } 377 | 378 | return wallet.getAddress() 379 | } 380 | } 381 | 382 | @Controller('/') 383 | class TestController { 384 | constructor(private readonly service: TestService) {} 385 | @Get() 386 | async get() { 387 | const address = await this.service.someMethod() 388 | 389 | return { address: address.toLowerCase() } 390 | } 391 | } 392 | 393 | @Module({ 394 | imports: [ 395 | EthersModule.forRootAsync({ 396 | useFactory: () => { 397 | return { 398 | useDefaultProvider: true, 399 | } 400 | }, 401 | }), 402 | ], 403 | controllers: [TestController], 404 | providers: [TestService], 405 | }) 406 | class TestModule {} 407 | 408 | const res = await appRequest(t, TestModule, PlatformAdapter) 409 | 410 | t.equal(res.statusCode, 200) 411 | t.same(res.body, { address: ETHERS_ADDRESS }) 412 | t.end() 413 | }) 414 | 415 | t.test('should create a wallet from a mnemonic with a provider injected', async (t) => { 416 | @Injectable() 417 | class TestService { 418 | constructor( 419 | @InjectSignerProvider() 420 | private readonly signer: EthersSigner, 421 | ) {} 422 | async someMethod(): Promise { 423 | const wallet = this.signer.createWalletfromMnemonic(Mnemonic.fromPhrase(ETHERS_MNEMONIC)) 424 | 425 | if (!(await wallet?.provider?.getNetwork())) { 426 | throw new Error('No provider injected') 427 | } 428 | 429 | return wallet.getAddress() 430 | } 431 | } 432 | 433 | @Controller('/') 434 | class TestController { 435 | constructor(private readonly service: TestService) {} 436 | @Get() 437 | async get() { 438 | const address = await this.service.someMethod() 439 | 440 | return { address: address.toLowerCase() } 441 | } 442 | } 443 | 444 | @Module({ 445 | imports: [ 446 | EthersModule.forRootAsync({ 447 | useFactory: () => { 448 | return { 449 | useDefaultProvider: true, 450 | } 451 | }, 452 | }), 453 | ], 454 | controllers: [TestController], 455 | providers: [TestService], 456 | }) 457 | class TestModule {} 458 | 459 | const res = await appRequest(t, TestModule, PlatformAdapter) 460 | 461 | t.equal(res.statusCode, 200) 462 | t.same(res.body, { address: ETHERS_ADDRESS }) 463 | t.end() 464 | }) 465 | 466 | t.test('should create a void signer from an address with a provider injected', async (t) => { 467 | @Injectable() 468 | class TestService { 469 | constructor( 470 | @InjectSignerProvider() 471 | private readonly signer: EthersSigner, 472 | ) {} 473 | async someMethod(): Promise { 474 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 475 | 476 | if (!(await wallet?.provider?.getNetwork())) { 477 | throw new Error('No provider injected') 478 | } 479 | 480 | return wallet.getAddress() 481 | } 482 | } 483 | 484 | @Controller('/') 485 | class TestController { 486 | constructor(private readonly service: TestService) {} 487 | @Get() 488 | async get() { 489 | const address = await this.service.someMethod() 490 | 491 | return { address: address.toLowerCase() } 492 | } 493 | } 494 | 495 | @Module({ 496 | imports: [ 497 | EthersModule.forRootAsync({ 498 | useFactory: () => { 499 | return { 500 | useDefaultProvider: true, 501 | } 502 | }, 503 | }), 504 | ], 505 | controllers: [TestController], 506 | providers: [TestService], 507 | }) 508 | class TestModule {} 509 | 510 | const res = await appRequest(t, TestModule, PlatformAdapter) 511 | 512 | t.equal(res.statusCode, 200) 513 | t.same(res.body, { address: ETHERS_ADDRESS }) 514 | t.end() 515 | }) 516 | 517 | t.end() 518 | }) 519 | 520 | t.end() 521 | }) 522 | } 523 | 524 | t.end() 525 | }) 526 | -------------------------------------------------------------------------------- /test/ethers.decorators.spec.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Injectable, Module } from '@nestjs/common' 2 | import { AbstractProvider, Contract, FallbackProvider, Network } from 'ethers' 3 | import * as nock from 'nock' 4 | import t from 'tap' 5 | import { 6 | EthersContract, 7 | EthersModule, 8 | EthersSigner, 9 | GOERLI_NETWORK, 10 | InjectContractProvider, 11 | InjectEthersProvider, 12 | InjectSignerProvider, 13 | } from '../src' 14 | import * as ABI from './utils/ABI.json' 15 | import { appRequest } from './utils/appRequest' 16 | import { ETHERS_ADDRESS, ETHERSCAN_V2_URL, GOERLI_ETHERSCAN_API_KEY } from './utils/constants' 17 | import { generateMethodQuery, RPC_RESPONSES } from './utils/mockResponses' 18 | import { platforms } from './utils/platforms' 19 | 20 | t.test('InjectEthersProvider', (t) => { 21 | t.beforeEach(() => nock.cleanAll()) 22 | 23 | t.before(() => { 24 | if (!nock.isActive()) { 25 | nock.activate() 26 | } 27 | 28 | nock.disableNetConnect() 29 | nock.enableNetConnect('127.0.0.1') 30 | }) 31 | 32 | t.after(() => nock.restore()) 33 | 34 | for (const PlatformAdapter of platforms) { 35 | t.test(PlatformAdapter.name, (t) => { 36 | t.test('forRoot', (t) => { 37 | t.test('should inject ethers provider in a service successfully', async (t) => { 38 | nock(ETHERSCAN_V2_URL) 39 | .persist() 40 | .get('/v2/api') 41 | .query( 42 | generateMethodQuery( 43 | 'eth_blockNumber', 44 | GOERLI_NETWORK.chainId.toString(), 45 | undefined, 46 | GOERLI_ETHERSCAN_API_KEY, 47 | ), 48 | ) 49 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 50 | 51 | @Injectable() 52 | class TestService { 53 | constructor( 54 | @InjectEthersProvider() 55 | private readonly ethersProvider: FallbackProvider, 56 | ) {} 57 | async someMethod(): Promise { 58 | const data = await this.ethersProvider.getNetwork() 59 | 60 | return data 61 | } 62 | } 63 | 64 | @Controller('/') 65 | class TestController { 66 | constructor(private readonly service: TestService) {} 67 | @Get() 68 | async get() { 69 | const network = await this.service.someMethod() 70 | 71 | return { name: network.name, chainId: Number(network.chainId) } 72 | } 73 | } 74 | 75 | @Module({ 76 | imports: [ 77 | EthersModule.forRoot({ 78 | network: GOERLI_NETWORK, 79 | etherscan: GOERLI_ETHERSCAN_API_KEY, 80 | useDefaultProvider: false, 81 | }), 82 | ], 83 | controllers: [TestController], 84 | providers: [TestService], 85 | }) 86 | class TestModule {} 87 | 88 | const res = await appRequest(t, TestModule, PlatformAdapter) 89 | 90 | t.equal(res.statusCode, 200) 91 | t.notHas(res.body, 'network') 92 | t.hasOwnProps(res.body, ['name', 'chainId']) 93 | t.equal(res.body.name, GOERLI_NETWORK.name) 94 | t.equal(res.body.chainId, Number(GOERLI_NETWORK.chainId)) 95 | t.end() 96 | }) 97 | 98 | t.test('should inject ethers provider in a controller successfully', async (t) => { 99 | nock(ETHERSCAN_V2_URL) 100 | .persist() 101 | .get('/v2/api') 102 | .query( 103 | generateMethodQuery( 104 | 'eth_blockNumber', 105 | GOERLI_NETWORK.chainId.toString(), 106 | undefined, 107 | GOERLI_ETHERSCAN_API_KEY, 108 | ), 109 | ) 110 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 111 | 112 | @Controller('/') 113 | class TestController { 114 | constructor( 115 | @InjectEthersProvider() 116 | private readonly ethersProvider: AbstractProvider, 117 | ) {} 118 | @Get() 119 | async get() { 120 | const network = await this.ethersProvider.getNetwork() 121 | 122 | return { name: network.name, chainId: Number(network.chainId) } 123 | } 124 | } 125 | 126 | @Module({ 127 | imports: [ 128 | EthersModule.forRoot({ 129 | network: GOERLI_NETWORK, 130 | etherscan: GOERLI_ETHERSCAN_API_KEY, 131 | useDefaultProvider: false, 132 | }), 133 | ], 134 | controllers: [TestController], 135 | }) 136 | class TestModule {} 137 | 138 | const res = await appRequest(t, TestModule, PlatformAdapter) 139 | 140 | t.equal(res.statusCode, 200) 141 | t.notHas(res.body, 'network') 142 | t.hasOwnProps(res.body, ['name', 'chainId']) 143 | t.equal(res.body.name, GOERLI_NETWORK.name) 144 | t.equal(res.body.chainId, Number(GOERLI_NETWORK.chainId)) 145 | t.end() 146 | }) 147 | 148 | t.test('should inject contract provider in a service successfully', async (t) => { 149 | nock(ETHERSCAN_V2_URL) 150 | .persist() 151 | .get('/v2/api') 152 | .query( 153 | generateMethodQuery( 154 | 'eth_blockNumber', 155 | GOERLI_NETWORK.chainId.toString(), 156 | undefined, 157 | GOERLI_ETHERSCAN_API_KEY, 158 | ), 159 | ) 160 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 161 | 162 | @Injectable() 163 | class TestService { 164 | constructor( 165 | @InjectContractProvider() 166 | private readonly contract: EthersContract, 167 | ) {} 168 | async someMethod(): Promise { 169 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 170 | 171 | return contract.getAddress() 172 | } 173 | } 174 | 175 | @Controller('/') 176 | class TestController { 177 | constructor(private readonly service: TestService) {} 178 | @Get() 179 | async get() { 180 | const address = await this.service.someMethod() 181 | 182 | return { address: address.toLowerCase() } 183 | } 184 | } 185 | 186 | @Module({ 187 | imports: [ 188 | EthersModule.forRoot({ 189 | network: GOERLI_NETWORK, 190 | etherscan: GOERLI_ETHERSCAN_API_KEY, 191 | useDefaultProvider: false, 192 | }), 193 | ], 194 | controllers: [TestController], 195 | providers: [TestService], 196 | }) 197 | class TestModule {} 198 | 199 | const res = await appRequest(t, TestModule, PlatformAdapter) 200 | 201 | t.equal(res.statusCode, 200) 202 | t.same(res.body, { address: ETHERS_ADDRESS }) 203 | t.end() 204 | }) 205 | 206 | t.test('should inject contract provider in a controller successfully', async (t) => { 207 | nock(ETHERSCAN_V2_URL) 208 | .persist() 209 | .get('/v2/api') 210 | .query( 211 | generateMethodQuery( 212 | 'eth_blockNumber', 213 | GOERLI_NETWORK.chainId.toString(), 214 | undefined, 215 | GOERLI_ETHERSCAN_API_KEY, 216 | ), 217 | ) 218 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 219 | 220 | @Controller('/') 221 | class TestController { 222 | constructor( 223 | @InjectContractProvider() 224 | private readonly contract: EthersContract, 225 | ) {} 226 | @Get() 227 | async get() { 228 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 229 | const address = await contract.getAddress() 230 | 231 | return { address: address.toLowerCase() } 232 | } 233 | } 234 | 235 | @Module({ 236 | imports: [ 237 | EthersModule.forRoot({ 238 | network: GOERLI_NETWORK, 239 | etherscan: GOERLI_ETHERSCAN_API_KEY, 240 | useDefaultProvider: false, 241 | }), 242 | ], 243 | controllers: [TestController], 244 | }) 245 | class TestModule {} 246 | 247 | const res = await appRequest(t, TestModule, PlatformAdapter) 248 | 249 | t.equal(res.statusCode, 200) 250 | t.same(res.body, { address: ETHERS_ADDRESS }) 251 | t.end() 252 | }) 253 | 254 | t.test('should inject signer provider in a service successfully', async (t) => { 255 | nock(ETHERSCAN_V2_URL) 256 | .persist() 257 | .get('/v2/api') 258 | .query( 259 | generateMethodQuery( 260 | 'eth_blockNumber', 261 | GOERLI_NETWORK.chainId.toString(), 262 | undefined, 263 | GOERLI_ETHERSCAN_API_KEY, 264 | ), 265 | ) 266 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 267 | 268 | @Injectable() 269 | class TestService { 270 | constructor( 271 | @InjectSignerProvider() 272 | private readonly signer: EthersSigner, 273 | ) {} 274 | async someMethod(): Promise { 275 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 276 | 277 | return wallet.getAddress() 278 | } 279 | } 280 | 281 | @Controller('/') 282 | class TestController { 283 | constructor(private readonly service: TestService) {} 284 | @Get() 285 | async get() { 286 | const address = await this.service.someMethod() 287 | 288 | return { address: address.toLowerCase() } 289 | } 290 | } 291 | 292 | @Module({ 293 | imports: [ 294 | EthersModule.forRoot({ 295 | network: GOERLI_NETWORK, 296 | etherscan: GOERLI_ETHERSCAN_API_KEY, 297 | useDefaultProvider: false, 298 | }), 299 | ], 300 | controllers: [TestController], 301 | providers: [TestService], 302 | }) 303 | class TestModule {} 304 | 305 | const res = await appRequest(t, TestModule, PlatformAdapter) 306 | 307 | t.equal(res.statusCode, 200) 308 | t.same(res.body, { address: ETHERS_ADDRESS }) 309 | t.end() 310 | }) 311 | 312 | t.test('should inject signer provider in a controller successfully', async (t) => { 313 | nock(ETHERSCAN_V2_URL) 314 | .persist() 315 | .get('/v2/api') 316 | .query( 317 | generateMethodQuery( 318 | 'eth_blockNumber', 319 | GOERLI_NETWORK.chainId.toString(), 320 | undefined, 321 | GOERLI_ETHERSCAN_API_KEY, 322 | ), 323 | ) 324 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 325 | 326 | @Controller('/') 327 | class TestController { 328 | constructor( 329 | @InjectSignerProvider() 330 | private readonly signer: EthersSigner, 331 | ) {} 332 | @Get() 333 | async get() { 334 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 335 | 336 | return { address: wallet.address.toLowerCase() } 337 | } 338 | } 339 | 340 | @Module({ 341 | imports: [ 342 | EthersModule.forRoot({ 343 | network: GOERLI_NETWORK, 344 | etherscan: GOERLI_ETHERSCAN_API_KEY, 345 | useDefaultProvider: false, 346 | }), 347 | ], 348 | controllers: [TestController], 349 | }) 350 | class TestModule {} 351 | 352 | const res = await appRequest(t, TestModule, PlatformAdapter) 353 | 354 | t.equal(res.statusCode, 200) 355 | t.same(res.body, { address: ETHERS_ADDRESS }) 356 | t.end() 357 | }) 358 | 359 | t.end() 360 | }) 361 | 362 | t.test('forRootAsync', (t) => { 363 | t.test('should inject ethers provider in a service successfully', async () => { 364 | nock(ETHERSCAN_V2_URL) 365 | .persist() 366 | .get('/v2/api') 367 | .query( 368 | generateMethodQuery( 369 | 'eth_blockNumber', 370 | GOERLI_NETWORK.chainId.toString(), 371 | undefined, 372 | GOERLI_ETHERSCAN_API_KEY, 373 | ), 374 | ) 375 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 376 | 377 | @Injectable() 378 | class TestService { 379 | constructor( 380 | @InjectEthersProvider() 381 | private readonly ethersProvider: FallbackProvider, 382 | ) {} 383 | async someMethod(): Promise { 384 | const data = await this.ethersProvider.getNetwork() 385 | 386 | return data 387 | } 388 | } 389 | 390 | @Controller('/') 391 | class TestController { 392 | constructor(private readonly service: TestService) {} 393 | @Get() 394 | async get() { 395 | const network = await this.service.someMethod() 396 | 397 | return { name: network.name, chainId: Number(network.chainId) } 398 | } 399 | } 400 | 401 | @Module({ 402 | imports: [ 403 | EthersModule.forRootAsync({ 404 | useFactory: () => { 405 | return { 406 | network: GOERLI_NETWORK, 407 | etherscan: GOERLI_ETHERSCAN_API_KEY, 408 | useDefaultProvider: false, 409 | } 410 | }, 411 | }), 412 | ], 413 | controllers: [TestController], 414 | providers: [TestService], 415 | }) 416 | class TestModule {} 417 | 418 | const res = await appRequest(t, TestModule, PlatformAdapter) 419 | 420 | t.equal(res.statusCode, 200) 421 | t.notHas(res.body, 'network') 422 | t.hasOwnProps(res.body, ['name', 'chainId']) 423 | t.equal(res.body.name, GOERLI_NETWORK.name) 424 | t.equal(res.body.chainId, Number(GOERLI_NETWORK.chainId)) 425 | t.end() 426 | }) 427 | 428 | t.test('should inject ethers provider in a controller successfully', async () => { 429 | nock(ETHERSCAN_V2_URL) 430 | .persist() 431 | .get('/v2/api') 432 | .query( 433 | generateMethodQuery( 434 | 'eth_blockNumber', 435 | GOERLI_NETWORK.chainId.toString(), 436 | undefined, 437 | GOERLI_ETHERSCAN_API_KEY, 438 | ), 439 | ) 440 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 441 | 442 | @Controller('/') 443 | class TestController { 444 | constructor( 445 | @InjectEthersProvider() 446 | private readonly ethersProvider: AbstractProvider, 447 | ) {} 448 | @Get() 449 | async get() { 450 | const network = await this.ethersProvider.getNetwork() 451 | 452 | return { name: network.name, chainId: Number(network.chainId) } 453 | } 454 | } 455 | 456 | @Module({ 457 | imports: [ 458 | EthersModule.forRootAsync({ 459 | useFactory: () => { 460 | return { 461 | network: GOERLI_NETWORK, 462 | etherscan: GOERLI_ETHERSCAN_API_KEY, 463 | useDefaultProvider: false, 464 | } 465 | }, 466 | }), 467 | ], 468 | controllers: [TestController], 469 | }) 470 | class TestModule {} 471 | 472 | const res = await appRequest(t, TestModule, PlatformAdapter) 473 | 474 | t.equal(res.statusCode, 200) 475 | t.notHas(res.body, 'network') 476 | t.hasOwnProps(res.body, ['name', 'chainId']) 477 | t.equal(res.body.name, GOERLI_NETWORK.name) 478 | t.equal(res.body.chainId, Number(GOERLI_NETWORK.chainId)) 479 | t.end() 480 | }) 481 | 482 | t.test('should inject contract provider in a service successfully', async () => { 483 | nock(ETHERSCAN_V2_URL) 484 | .persist() 485 | .get('/v2/api') 486 | .query( 487 | generateMethodQuery( 488 | 'eth_blockNumber', 489 | GOERLI_NETWORK.chainId.toString(), 490 | undefined, 491 | GOERLI_ETHERSCAN_API_KEY, 492 | ), 493 | ) 494 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 495 | 496 | @Injectable() 497 | class TestService { 498 | constructor( 499 | @InjectContractProvider() 500 | private readonly contract: EthersContract, 501 | ) {} 502 | async someMethod(): Promise { 503 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 504 | 505 | return contract.getAddress() 506 | } 507 | } 508 | 509 | @Controller('/') 510 | class TestController { 511 | constructor(private readonly service: TestService) {} 512 | @Get() 513 | async get() { 514 | const address = await this.service.someMethod() 515 | 516 | return { address: address.toLowerCase() } 517 | } 518 | } 519 | 520 | @Module({ 521 | imports: [ 522 | EthersModule.forRootAsync({ 523 | useFactory: () => { 524 | return { 525 | network: GOERLI_NETWORK, 526 | etherscan: GOERLI_ETHERSCAN_API_KEY, 527 | useDefaultProvider: false, 528 | } 529 | }, 530 | }), 531 | ], 532 | controllers: [TestController], 533 | providers: [TestService], 534 | }) 535 | class TestModule {} 536 | 537 | const res = await appRequest(t, TestModule, PlatformAdapter) 538 | 539 | t.equal(res.statusCode, 200) 540 | t.same(res.body, { address: ETHERS_ADDRESS }) 541 | t.end() 542 | }) 543 | 544 | t.test('should inject contract provider in a controller successfully', async () => { 545 | nock(ETHERSCAN_V2_URL) 546 | .persist() 547 | .get('/v2/api') 548 | .query( 549 | generateMethodQuery( 550 | 'eth_blockNumber', 551 | GOERLI_NETWORK.chainId.toString(), 552 | undefined, 553 | GOERLI_ETHERSCAN_API_KEY, 554 | ), 555 | ) 556 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 557 | 558 | @Controller('/') 559 | class TestController { 560 | constructor( 561 | @InjectContractProvider() 562 | private readonly contract: EthersContract, 563 | ) {} 564 | @Get() 565 | async get() { 566 | const contract: Contract = this.contract.create(ETHERS_ADDRESS, ABI) 567 | const address = await contract.getAddress() 568 | 569 | return { address: address.toLowerCase() } 570 | } 571 | } 572 | 573 | @Module({ 574 | imports: [ 575 | EthersModule.forRootAsync({ 576 | useFactory: () => { 577 | return { 578 | network: GOERLI_NETWORK, 579 | etherscan: GOERLI_ETHERSCAN_API_KEY, 580 | useDefaultProvider: false, 581 | } 582 | }, 583 | }), 584 | ], 585 | controllers: [TestController], 586 | }) 587 | class TestModule {} 588 | 589 | const res = await appRequest(t, TestModule, PlatformAdapter) 590 | 591 | t.equal(res.statusCode, 200) 592 | t.same(res.body, { address: ETHERS_ADDRESS }) 593 | t.end() 594 | }) 595 | 596 | t.test('should inject signer provider in a service successfully', async () => { 597 | nock(ETHERSCAN_V2_URL) 598 | .persist() 599 | .get('/v2/api') 600 | .query( 601 | generateMethodQuery( 602 | 'eth_blockNumber', 603 | GOERLI_NETWORK.chainId.toString(), 604 | undefined, 605 | GOERLI_ETHERSCAN_API_KEY, 606 | ), 607 | ) 608 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 609 | 610 | @Injectable() 611 | class TestService { 612 | constructor( 613 | @InjectSignerProvider() 614 | private readonly signer: EthersSigner, 615 | ) {} 616 | async someMethod(): Promise { 617 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 618 | 619 | return wallet.getAddress() 620 | } 621 | } 622 | 623 | @Controller('/') 624 | class TestController { 625 | constructor(private readonly service: TestService) {} 626 | @Get() 627 | async get() { 628 | const address = await this.service.someMethod() 629 | 630 | return { address: address.toLowerCase() } 631 | } 632 | } 633 | 634 | @Module({ 635 | imports: [ 636 | EthersModule.forRootAsync({ 637 | useFactory: () => { 638 | return { 639 | network: GOERLI_NETWORK, 640 | etherscan: GOERLI_ETHERSCAN_API_KEY, 641 | useDefaultProvider: false, 642 | } 643 | }, 644 | }), 645 | ], 646 | controllers: [TestController], 647 | providers: [TestService], 648 | }) 649 | class TestModule {} 650 | 651 | const res = await appRequest(t, TestModule, PlatformAdapter) 652 | 653 | t.equal(res.statusCode, 200) 654 | t.same(res.body, { address: ETHERS_ADDRESS }) 655 | t.end() 656 | }) 657 | 658 | t.test('should inject signer provider in a controller successfully', async () => { 659 | nock(ETHERSCAN_V2_URL) 660 | .persist() 661 | .get('/v2/api') 662 | .query( 663 | generateMethodQuery( 664 | 'eth_blockNumber', 665 | GOERLI_NETWORK.chainId.toString(), 666 | undefined, 667 | GOERLI_ETHERSCAN_API_KEY, 668 | ), 669 | ) 670 | .reply(200, RPC_RESPONSES['eth_blockNumber']) 671 | 672 | @Controller('/') 673 | class TestController { 674 | constructor( 675 | @InjectSignerProvider() 676 | private readonly signer: EthersSigner, 677 | ) {} 678 | @Get() 679 | async get() { 680 | const wallet = this.signer.createVoidSigner(ETHERS_ADDRESS) 681 | 682 | return { address: wallet.address.toLowerCase() } 683 | } 684 | } 685 | 686 | @Module({ 687 | imports: [ 688 | EthersModule.forRootAsync({ 689 | useFactory: () => { 690 | return { 691 | network: GOERLI_NETWORK, 692 | etherscan: GOERLI_ETHERSCAN_API_KEY, 693 | useDefaultProvider: false, 694 | } 695 | }, 696 | }), 697 | ], 698 | controllers: [TestController], 699 | }) 700 | class TestModule {} 701 | 702 | const res = await appRequest(t, TestModule, PlatformAdapter) 703 | 704 | t.equal(res.statusCode, 200) 705 | t.same(res.body, { address: ETHERS_ADDRESS }) 706 | t.end() 707 | }) 708 | 709 | t.end() 710 | }) 711 | 712 | t.end() 713 | }) 714 | } 715 | 716 | t.end() 717 | }) 718 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | NestJS-Ethers 2 | ============= 3 | 4 | [![npm](https://img.shields.io/npm/v/nestjs-ethers)](https://www.npmjs.com/package/nestjs-ethers) 5 | [![CircleCI](https://circleci.com/gh/blockcoders/nestjs-ethers/tree/main.svg?style=svg)](https://circleci.com/gh/blockcoders/nestjs-ethers/tree/main) 6 | [![Coverage Status](https://coveralls.io/repos/github/blockcoders/nestjs-ethers/badge.svg?branch=main)](https://coveralls.io/github/blockcoders/nestjs-ethers?branch=main) 7 | [![vulnerabilities](https://badgen.net/snyk/blockcoders/nestjs-ethers)](https://snyk.io/test/github/blockcoders/nestjs-ethers) 8 | [![CodeQL](https://github.com/blockcoders/nestjs-ethers/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/blockcoders/nestjs-ethers/actions/workflows/codeql-analysis.yml) 9 | [![supported platforms](https://img.shields.io/badge/platforms-Express%20%26%20Fastify-green)](https://img.shields.io/badge/platforms-Express%20%26%20Fastify-green) 10 | 11 | 12 | Ethereum utilities for NestJS based on [Ethers.js](https://github.com/ethers-io/ethers.js/) 13 | 14 | ## Install 15 | 16 | ```sh 17 | npm i nestjs-ethers 18 | ``` 19 | 20 | ## Register module 21 | 22 | ### Zero configuration 23 | 24 | Just import `EthersModule` to your module: 25 | 26 | ```ts 27 | import { EthersModule } from 'nestjs-ethers'; 28 | 29 | @Module({ 30 | imports: [EthersModule.forRoot()], 31 | ... 32 | }) 33 | class MyModule {} 34 | ``` 35 | 36 | **NOTE:** *By default `EthersModule` will try to connect using [getDefaultProvider](https://docs.ethers.org/v6/api/providers/#getDefaultProvider). It's the safest, easiest way to begin developing on Ethereum. It creates a [FallbackProvider](https://docs.ethers.org/v6/api/providers/fallback-provider/) connected to as many backend services as possible.* 37 | 38 | ### Configuration params 39 | 40 | `nestjs-ethers` can be configured with this options: 41 | 42 | ```ts 43 | interface EthersModuleOptions { 44 | /** 45 | * Optional parameter for connection, can be a Network object 46 | * or the name of a common network as a string (e.g. "homestead") 47 | * If no network is provided, homestead (i.e. mainnet) is used. 48 | * The network may also be a URL to connect to, 49 | * such as http://localhost:8545 or wss://example.com. 50 | * @see {@link https://docs.ethers.org/v6/api/providers/#Networkish} 51 | */ 52 | network?: Networkish; 53 | 54 | /** 55 | * Optional parameter for Alchemy API Token 56 | * @see {@link https://alchemyapi.io} 57 | */ 58 | alchemy?: string; 59 | 60 | /** 61 | * Optional parameter for Etherscan API Token 62 | * @see {@link https://etherscan.io} 63 | */ 64 | etherscan?: string; 65 | 66 | /** 67 | * Optional parameter for Bscscan API Token 68 | * @see {@link https://bscscan.com/} 69 | */ 70 | bscscan?: string; 71 | 72 | /** 73 | * Optional parameter for use Cloudflare Provider 74 | * @see {@link https://cloudflare-eth.com} 75 | */ 76 | cloudflare?: boolean; 77 | 78 | /** 79 | * Optional parameter for Infura Project ID 80 | * or InfuraProviderOptions(applicationId, applicationSecretKey) 81 | * @see {@link https://infura.io} 82 | */ 83 | infura?: InfuraProviderOptions | string; 84 | 85 | /** 86 | * Optional parameter for Pocket Network Application ID 87 | * or PocketProviderOptions(projectId, projectSecret) 88 | * @see {@link https://pokt.network} 89 | */ 90 | pocket?: PocketProviderOptions | string; 91 | 92 | /** 93 | * Optional parameter for Moralis API Token 94 | * or MoralisProviderOptions(apiKey, region) 95 | * @see {@link https://moralis.io/} 96 | */ 97 | moralis?: MoralisProviderOptions | string; 98 | 99 | /** 100 | * Optional parameter for Ankr API Token 101 | * or AnkrProviderOptions(apiKey, projectSecret) 102 | * @see {@link https://www.ankr.com/} 103 | */ 104 | ankr?: AnkrProviderOptions | string; 105 | 106 | /** 107 | * Optional parameter for a custom JsonRpcProvider 108 | * You can connect using an URL, FetchRequest or an array of both. 109 | * @see {@link https://docs.ethers.org/v6/api/providers/jsonrpc/} 110 | * @ses {@link https://docs.ethers.org/v6/api/utils/fetching/#FetchRequest} 111 | */ 112 | custom?: string | FetchRequest | (string | FetchRequest)[] 113 | 114 | /** 115 | * Optional parameter the number of backends that must agree 116 | * (default: 2 for mainnet, 1 for testnets) 117 | */ 118 | quorum?: number; 119 | 120 | /** 121 | * Optional parameter if this option is false, EthersModule will try to connect 122 | * with the credentials provided in options. If you define more than one provider, 123 | * EthersModule will use the FallbackProvider to send multiple requests simultaneously. 124 | */ 125 | useDefaultProvider?: boolean; 126 | 127 | /** 128 | * Optional parameter to associate a token name to EthersProvider, 129 | * the token is used to request an instance of a class by the same name. 130 | * This can be useful when you want multiple intances of EthersProvider. 131 | */ 132 | token?: string; 133 | } 134 | ``` 135 | 136 | ### Synchronous configuration 137 | 138 | Use `EthersModule.forRoot` method with [Options interface](#configuration-params): 139 | 140 | ```ts 141 | import { EthersModule, RINKEBY_NETWORK } from 'nestjs-ethers'; 142 | 143 | @Module({ 144 | imports: [ 145 | EthersModule.forRoot({ 146 | network: RINKEBY_NETWORK, 147 | alchemy: '845ce4ed0120d68eb5740c9160f08f98', 148 | etherscan: 'e8cce313c1cfbd085f68be509451f1bab8', 149 | cloudflare: true, 150 | infura: { 151 | projectId: 'd71b3d93c2fcfa7cab4924e63298575a', 152 | projectSecret: 'ed6baa9f7a09877998a24394a12bf3dc', 153 | }, 154 | pocket: { 155 | applicationId: '9b0afc55221c429104d04ef9', 156 | applicationSecretKey: 'b5e6d6a55426712a42a93f39555973fc', 157 | }, 158 | quorum: 1, 159 | useDefaultProvider: true, 160 | }) 161 | ], 162 | ... 163 | }) 164 | class MyModule {} 165 | ``` 166 | 167 | ### Asynchronous configuration 168 | 169 | With `EthersModule.forRootAsync` you can, for example, import your `ConfigModule` and inject `ConfigService` to use it in `useFactory` method. 170 | 171 | `useFactory` should return object with [Options interface](#configuration-params) or undefined 172 | 173 | Here's an example: 174 | 175 | ```ts 176 | import { EthersModule, RINKEBY_NETWORK } from 'nestjs-ethers'; 177 | 178 | @Injectable() 179 | class ConfigService { 180 | public readonly infura = { 181 | projectId: 'd71b3d93c2fcfa7cab4924e63298575a', 182 | projectSecret: 'ed6baa9f7a09877998a24394a12bf3dc', 183 | }; 184 | } 185 | 186 | @Module({ 187 | providers: [ConfigService], 188 | exports: [ConfigService] 189 | }) 190 | class ConfigModule {} 191 | 192 | @Module({ 193 | imports: [ 194 | EthersModule.forRootAsync({ 195 | imports: [ConfigModule], 196 | inject: [ConfigService], 197 | useFactory: async (config: ConfigService) => { 198 | await somePromise(); 199 | return { 200 | network: RINKEBY_NETWORK, 201 | infura: config.infura, 202 | useDefaultProvider: false, 203 | }; 204 | } 205 | }) 206 | ], 207 | ... 208 | }) 209 | class TestModule {} 210 | ``` 211 | 212 | Or you can just pass `ConfigService` to `providers`, if you don't have any `ConfigModule`: 213 | 214 | ```ts 215 | import { EthersModule, RINKEBY_NETWORK } from 'nestjs-ethers'; 216 | 217 | @Injectable() 218 | class ConfigService { 219 | public readonly pocket: { 220 | applicationId: '9b0afc55221c429104d04ef9', 221 | applicationSecretKey: 'b5e6d6a55426712a42a93f39555973fc', 222 | }; 223 | } 224 | 225 | @Module({ 226 | imports: [ 227 | EthersModule.forRootAsync({ 228 | providers: [ConfigService], 229 | inject: [ConfigService], 230 | useFactory: (config: ConfigService) => { 231 | return { 232 | network: RINKEBY_NETWORK, 233 | pocket: config.pocket, 234 | useDefaultProvider: false, 235 | }; 236 | } 237 | }) 238 | ], 239 | controllers: [TestController] 240 | }) 241 | class TestModule {} 242 | ``` 243 | 244 | You can also pass multiple `ethersjs` configs, if you want to use the `FallbackProvider` to send multiple requests simultaneously: 245 | 246 | ```ts 247 | import { EthersModule, RINKEBY_NETWORK } from 'nestjs-ethers'; 248 | 249 | @Injectable() 250 | class ConfigService { 251 | public readonly infura = { 252 | projectId: 'd71b3d93c2fcfa7cab4924e63298575a', 253 | projectSecret: 'ed6baa9f7a09877998a24394a12bf3dc', 254 | }; 255 | public readonly pocket: { 256 | applicationId: '9b0afc55221c429104d04ef9', 257 | applicationSecretKey: 'b5e6d6a55426712a42a93f39555973fc', 258 | }; 259 | } 260 | 261 | @Module({ 262 | providers: [ConfigService], 263 | exports: [ConfigService] 264 | }) 265 | class ConfigModule {} 266 | 267 | @Module({ 268 | imports: [ 269 | EthersModule.forRootAsync({ 270 | imports: [ConfigModule], 271 | inject: [ConfigService], 272 | useFactory: async (config: ConfigService) => { 273 | await somePromise(); 274 | return { 275 | network: RINKEBY_NETWORK, 276 | infura: config.infura, 277 | pocket: config.pocket, 278 | useDefaultProvider: false, 279 | }; 280 | } 281 | }) 282 | ], 283 | ... 284 | }) 285 | class TestModule {} 286 | ``` 287 | 288 | ## BaseProvider 289 | 290 | `BaseProvider` implements standard [Ether.js Provider](https://docs.ethers.org/v6/api/providers/#Provider). So if you are familiar with it, you are ready to go. 291 | 292 | ```ts 293 | import { InjectEthersProvider, BaseProvider } from 'nestjs-ethers'; 294 | 295 | @Injectable() 296 | export class TestService { 297 | constructor( 298 | @InjectEthersProvider() 299 | private readonly ethersProvider: BaseProvider, 300 | ) {} 301 | async someMethod(): Promise { 302 | return this.ethersProvider.getNetwork(); 303 | } 304 | } 305 | ``` 306 | 307 | ## Binance Smart Chain Provider 308 | 309 | if you are familiar with [BscscanProvider](https://github.com/ethers-io/ancillary-bsc), you are ready to go. 310 | 311 | ```ts 312 | import { 313 | EthersModule, 314 | InjectEthersProvider, 315 | BscscanProvider, 316 | BINANCE_NETWORK 317 | } from 'nestjs-ethers'; 318 | 319 | @Module({ 320 | imports: [ 321 | EthersModule.forRoot({ 322 | network: BINANCE_NETWORK, 323 | bscscan: '845ce4ed0120d68eb5740c9160f08f98', 324 | useDefaultProvider: false, 325 | }) 326 | ], 327 | ... 328 | }) 329 | class MyModule {} 330 | 331 | @Controller('/') 332 | class TestController { 333 | constructor( 334 | @InjectEthersProvider() 335 | private readonly bscProvider: BscscanProvider, 336 | ) {} 337 | @Get() 338 | async get() { 339 | const gasPrice: BigNumber = await this.bscProvider.getGasPrice() 340 | 341 | return { gasPrice: gasPrice.toString() } 342 | } 343 | } 344 | ``` 345 | 346 | ### Binance Smart Chain Default Provider 347 | 348 | This will create a `FallbackProvider`, backed by all popular Third-Party BSC services (currently only [BscscanProvider](https://github.com/ethers-io/ancillary-bsc)). 349 | 350 | **NOTE:** if `bscscan` is null or undefined. The BSC default provider will use the [community API Key](https://github.com/ethers-io/ancillary-bsc/blob/main/src.ts/bscscan-provider.ts#L8). 351 | 352 | ```ts 353 | import { 354 | EthersModule, 355 | InjectEthersProvider, 356 | FallbackProvider, 357 | BINANCE_NETWORK 358 | } from 'nestjs-ethers'; 359 | 360 | @Module({ 361 | imports: [ 362 | EthersModule.forRoot({ 363 | network: BINANCE_NETWORK, 364 | useDefaultProvider: true, 365 | }) 366 | ], 367 | ... 368 | }) 369 | class MyModule {} 370 | 371 | @Controller('/') 372 | class TestController { 373 | constructor( 374 | @InjectEthersProvider() 375 | private readonly bscProvider: FallbackProvider, 376 | ) {} 377 | @Get() 378 | async get() { 379 | const gasPrice: BigNumber = await this.bscProvider.getGasPrice() 380 | 381 | return { gasPrice: gasPrice.toString() } 382 | } 383 | } 384 | ``` 385 | 386 | ## Custom JsonRpcProvider 387 | 388 | if you are familiar with [JsonRpcProvider](https://docs.ethers.org/v6/api/providers/jsonrpc/), you are ready to go. The custom provider is very helpful when you want to use a RPC that is not defined in [ethers](https://github.com/ethers-io/ethers.js/). This is the case for Binance Smart Chain public [RPCs](https://docs.binance.org/smart-chain/developer/rpc.html). 389 | 390 | ```ts 391 | import { 392 | EthersModule, 393 | InjectEthersProvider, 394 | StaticJsonRpcProvider, 395 | BNB_TESTNET_NETWORK 396 | } from 'nestjs-ethers'; 397 | 398 | @Module({ 399 | imports: [ 400 | EthersModule.forRoot({ 401 | network: BNB_TESTNET_NETWORK, 402 | custom: 'https://data-seed-prebsc-1-s1.binance.org:8545', 403 | useDefaultProvider: false, 404 | }) 405 | ], 406 | ... 407 | }) 408 | class MyModule {} 409 | 410 | @Controller('/') 411 | class TestController { 412 | constructor( 413 | @InjectEthersProvider() 414 | private readonly customProvider: StaticJsonRpcProvider, 415 | ) {} 416 | @Get() 417 | async get() { 418 | const gasPrice: BigNumber = await this.customProvider.getGasPrice() 419 | 420 | return { gasPrice: gasPrice.toString() } 421 | } 422 | } 423 | ``` 424 | 425 | You can also pass multiple `custom` providers, if you want to use the `FallbackProvider` to send multiple requests simultaneously: 426 | 427 | ```ts 428 | import { 429 | EthersModule, 430 | InjectEthersProvider, 431 | FallbackProvider, 432 | BNB_TESTNET_NETWORK 433 | } from 'nestjs-ethers'; 434 | 435 | @Module({ 436 | imports: [ 437 | EthersModule.forRoot({ 438 | network: BNB_TESTNET_NETWORK, 439 | custom: [ 440 | 'https://data-seed-prebsc-1-s1.binance.org:8545', 441 | 'https://data-seed-prebsc-1-s3.binance.org:8545', 442 | 'https://data-seed-prebsc-2-s2.binance.org:8545' 443 | ], 444 | useDefaultProvider: false, 445 | }) 446 | ], 447 | ... 448 | }) 449 | class MyModule {} 450 | 451 | @Controller('/') 452 | class TestController { 453 | constructor( 454 | @InjectEthersProvider() 455 | private readonly customProvider: FallbackProvider, 456 | ) {} 457 | @Get() 458 | async get() { 459 | const gasPrice: BigNumber = await this.customProvider.getGasPrice() 460 | 461 | return { gasPrice: gasPrice.toString() } 462 | } 463 | } 464 | ``` 465 | 466 | ## EthersSigner 467 | 468 | `EthersSigner` implements methods to create a [Wallet](https://docs.ethers.org/v6/api/wallet/#Wallet) or [VoidSigner](https://docs.ethers.org/v6/api/providers/abstract-signer/#VoidSigner). A `Signer` in ethers is an abstraction of an Ethereum Account, which can be used to sign messages and transactions and send signed transactions to the Ethereum Network. This service will also inject the `BaseProvider` into the wallet. 469 | 470 | Create a `Wallet` from a private key: 471 | 472 | ```ts 473 | import { EthersSigner, InjectSignerProvider, Wallet } from 'nestjs-ethers'; 474 | 475 | @Injectable() 476 | export class TestService { 477 | constructor( 478 | @InjectSignerProvider() 479 | private readonly ethersSigner: EthersSigner, 480 | ) {} 481 | async someMethod(): Promise { 482 | const wallet: Wallet = this.ethersSigner.createWallet( 483 | '0x4c94faa2c558a998d10ee8b2b9b8eb1fbcb8a6ac5fd085c6f95535604fc1bffb' 484 | ); 485 | 486 | return wallet.getAddress(); 487 | } 488 | } 489 | ``` 490 | 491 | Create a random [Wallet](https://docs.ethers.org/v6/api/wallet/#Wallet_createRandom): 492 | 493 | ```ts 494 | import { EthersSigner, InjectSignerProvider, Wallet } from 'nestjs-ethers'; 495 | 496 | @Injectable() 497 | export class TestService { 498 | constructor( 499 | @InjectSignerProvider() 500 | private readonly ethersSigner: EthersSigner, 501 | ) {} 502 | async someMethod(): Promise { 503 | const wallet: Wallet = this.ethersSigner.createRandomWallet(); 504 | 505 | return wallet.getAddress(); 506 | } 507 | } 508 | ``` 509 | 510 | Create a [Wallet](https://docs.ethers.org/v6/api/wallet/#Wallet_fromEncryptedJson) from an encrypted JSON: 511 | 512 | ```ts 513 | import { EthersSigner, InjectSignerProvider, Wallet } from 'nestjs-ethers'; 514 | 515 | @Injectable() 516 | export class TestService { 517 | constructor( 518 | @InjectSignerProvider() 519 | private readonly ethersSigner: EthersSigner, 520 | ) {} 521 | async someMethod(): Promise { 522 | const wallet: Wallet = this.ethersSigner.createWalletFromEncryptedJson( 523 | { 524 | address: '012363d61bdc53d0290a0f25e9c89f8257550fb8', 525 | id: '5ba8719b-faf9-49ec-8bca-21522e3d56dc', 526 | version: 3, 527 | Crypto: { 528 | cipher: 'aes-128-ctr', 529 | cipherparams: { iv: 'bc0473d60284d2d6994bb6793e916d06' }, 530 | ciphertext: 531 | 'e73ed0b0c53bcaea4516a15faba3f6d76dbe71b9b46a460ed7e04a68e0867dd7', 532 | kdf: 'scrypt', 533 | kdfparams: { 534 | salt: '97f0b6e17c392f76a726ceea02bac98f17265f1aa5cf8f9ad1c2b56025bc4714', 535 | n: 131072, 536 | dklen: 32, 537 | p: 1, 538 | r: 8, 539 | }, 540 | mac: 'ff4f2db7e7588f8dd41374d7b98dfd7746b554c0099a6c0765be7b1c7913e1f3', 541 | }, 542 | 'x-ethers': { 543 | client: 'ethers.js', 544 | gethFilename: 'UTC--2018-01-27T01-52-22.0Z--012363d61bdc53d0290a0f25e9c89f8257550fb8', 545 | mnemonicCounter: '70224accc00e35328a010a19fef51121', 546 | mnemonicCiphertext: 'cf835e13e4f90b190052263dbd24b020', 547 | version: '0.1', 548 | }, 549 | }, 550 | 'password' 551 | ); 552 | 553 | return wallet.getAddress(); 554 | } 555 | } 556 | ``` 557 | 558 | Create a [Wallet](https://docs.ethers.org/v6/api/wallet/#Wallet_fromPhrase) from a mnemonic: 559 | 560 | ```ts 561 | import { EthersSigner, InjectSignerProvider, Wallet } from 'nestjs-ethers'; 562 | 563 | @Injectable() 564 | export class TestService { 565 | constructor( 566 | @InjectSignerProvider() 567 | private readonly ethersSigner: EthersSigner, 568 | ) {} 569 | async someMethod(): Promise { 570 | const wallet: Wallet = this.ethersSigner.createWalletfromMnemonic( 571 | 'service basket parent alcohol fault similar survey twelve hockey cloud walk panel' 572 | ); 573 | 574 | return wallet.getAddress(); 575 | } 576 | } 577 | ``` 578 | 579 | Create a [VoidSigner](https://docs.ethers.org/v6/api/providers/#Signer) from an address: 580 | 581 | ```ts 582 | import { EthersSigner, InjectSignerProvider, VoidSigner } from 'nestjs-ethers'; 583 | 584 | @Injectable() 585 | export class TestService { 586 | constructor( 587 | @InjectSignerProvider() 588 | private readonly ethersSigner: EthersSigner, 589 | ) {} 590 | async someMethod(): Promise { 591 | const wallet: VoidSigner = this.ethersSigner.createVoidSigner( 592 | '0x012363d61bdc53d0290a0f25e9c89f8257550fb8' 593 | ); 594 | 595 | return wallet.getAddress(); 596 | } 597 | } 598 | ``` 599 | 600 | ## EthersContract 601 | 602 | `EthersContract` implements a method for the creation of a [Contract](https://docs.ethers.org/v6/api/contract/) instance. This service will also inject the a `BaseProvider` into the contract. 603 | 604 | Create a `SmartContract` attached to an address: 605 | 606 | ```ts 607 | import { EthersContract, InjectContractProvider, Contract, Network } from 'nestjs-ethers'; 608 | import * as ABI from './utils/ABI.json'; 609 | 610 | @Injectable() 611 | class TestService { 612 | constructor( 613 | @InjectContractProvider() 614 | private readonly ethersContract: EthersContract, 615 | ) {} 616 | async someMethod(): Promise { 617 | const contract: Contract = this.ethersContract.create( 618 | '0x012363d61bdc53d0290a0f25e9c89f8257550fb8', 619 | ABI, 620 | ); 621 | 622 | return contract.provider.getNetwork(); 623 | } 624 | } 625 | ``` 626 | 627 | Create a [Contract](https://docs.ethers.org/v6/api/contract/) with a Wallet: 628 | 629 | ```ts 630 | import { 631 | EthersContract, 632 | EthersSigner, 633 | InjectContractProvider, 634 | InjectSignerProvider, 635 | Contract, 636 | Network, 637 | Wallet 638 | } from 'nestjs-ethers'; 639 | import * as ABI from './utils/ABI.json'; 640 | 641 | @Injectable() 642 | class TestService { 643 | constructor( 644 | @InjectContractProvider() 645 | private readonly ethersContract: EthersContract, 646 | @InjectSignerProvider() 647 | private readonly ethersSigner: EthersSigner, 648 | ) {} 649 | async someMethod(): Promise { 650 | const wallet: Wallet = this.ethersSigner.createWallet( 651 | '0x4c94faa2c558a998d10ee8b2b9b8eb1fbcb8a6ac5fd085c6f95535604fc1bffb' 652 | ); 653 | const contract: Contract = this.ethersContract.create( 654 | '0x012363d61bdc53d0290a0f25e9c89f8257550fb8', 655 | ABI, 656 | wallet, 657 | ); 658 | 659 | return contract.signer.provider.getNetwork(); 660 | } 661 | } 662 | ``` 663 | 664 | ## Multichain mode 665 | 666 | You can use the `token` property to use multiple instances of Ethers. This can be helpful when you want to connect with more than one EVN compatible chain like `BSC`, `Polygon` or `Fantom`. 667 | 668 | If you know what you're doing, you can enable it like so: 669 | 670 | ### Synchronous 671 | 672 | ```ts 673 | import { Module, Controller, Get } from '@nestjs/common' 674 | import { 675 | EthersModule, 676 | InjectEthersProvider, 677 | InjectEthersProvider, 678 | InjectEthersProvider, 679 | PocketProvider, 680 | AlchemyProvider, 681 | StaticJsonRpcProvider, 682 | BigNumber, 683 | RINKEBY_NETWORK, 684 | MUMBAI_NETWORK, 685 | BNB_TESTNET_NETWORK, 686 | } from 'nestjs-ethers'; 687 | 688 | @Controller('/') 689 | class TestController { 690 | constructor( 691 | @InjectEthersProvider('eth') 692 | private readonly pocketProvider: PocketProvider, 693 | @InjectEthersProvider('poly') 694 | private readonly alchemyProvider: AlchemyProvider, 695 | @InjectEthersProvider('bsc') 696 | private readonly customProvider: StaticJsonRpcProvider, 697 | ) {} 698 | @Get() 699 | async get() { 700 | const pocketGasPrice: BigNumber = await this.pocketProvider.getGasPrice() 701 | const alchemyGasPrice: BigNumber = await this.alchemyProvider.getGasPrice() 702 | const bscGasPrice: BigNumber = await this.customProvider.getGasPrice() 703 | 704 | return { 705 | pocketGasPrice: pocketGasPrice.toString(), 706 | alchemyGasPrice: alchemyGasPrice.toString(), 707 | bscGasPrice: bscGasPrice.toString(), 708 | } 709 | } 710 | } 711 | 712 | @Module({ 713 | imports: [ 714 | EthersModule.forRoot({ 715 | token: 'eth', 716 | network: RINKEBY_NETWORK, 717 | pocket: { 718 | applicationId: '9b0afc55221c429104d04ef9', 719 | applicationSecretKey: 'b5e6d6a55426712a42a93f39555973fc', 720 | }, 721 | useDefaultProvider: false, 722 | }), 723 | EthersModule.forRoot({ 724 | token: 'poly', 725 | network: MUMBAI_NETWORK, 726 | alchemy: '845ce4ed0120d68eb5740c9160f08f98', 727 | useDefaultProvider: false, 728 | }), 729 | EthersModule.forRoot({ 730 | token: 'bsc', 731 | network: BNB_TESTNET_NETWORK, 732 | custom: 'https://data-seed-prebsc-1-s1.binance.org:8545', 733 | useDefaultProvider: false, 734 | }), 735 | ], 736 | controllers: [TestController], 737 | }) 738 | class TestModule {} 739 | ``` 740 | 741 | ### Asynchronous configuration 742 | 743 | ```ts 744 | import { Module, Controller, Get } from '@nestjs/common' 745 | import { 746 | EthersModule, 747 | InjectEthersProvider, 748 | InjectEthersProvider, 749 | InjectEthersProvider, 750 | PocketProvider, 751 | AlchemyProvider, 752 | StaticJsonRpcProvider, 753 | BigNumber, 754 | RINKEBY_NETWORK, 755 | MUMBAI_NETWORK, 756 | BNB_TESTNET_NETWORK, 757 | } from 'nestjs-ethers'; 758 | 759 | @Controller('/') 760 | class TestController { 761 | constructor( 762 | @InjectEthersProvider('eth') 763 | private readonly pocketProvider: PocketProvider, 764 | @InjectEthersProvider('poly') 765 | private readonly alchemyProvider: AlchemyProvider, 766 | @InjectEthersProvider('bsc') 767 | private readonly customProvider: StaticJsonRpcProvider, 768 | ) {} 769 | @Get() 770 | async get() { 771 | const pocketGasPrice: BigNumber = await this.pocketProvider.getGasPrice() 772 | const alchemyGasPrice: BigNumber = await this.alchemyProvider.getGasPrice() 773 | const bscGasPrice: BigNumber = await this.customProvider.getGasPrice() 774 | 775 | return { 776 | pocketGasPrice: pocketGasPrice.toString(), 777 | alchemyGasPrice: alchemyGasPrice.toString(), 778 | bscGasPrice: bscGasPrice.toString(), 779 | } 780 | } 781 | } 782 | 783 | @Injectable() 784 | class ConfigService { 785 | public readonly applicationId: '9b0afc55221c429104d04ef9' 786 | public readonly applicationSecretKey: 'b5e6d6a55426712a42a93f39555973fc' 787 | public readonly alchemy: '845ce4ed0120d68eb5740c9160f08f98' 788 | public readonly custom: 'https://data-seed-prebsc-1-s1.binance.org:8545' 789 | } 790 | 791 | @Module({ 792 | providers: [ConfigService], 793 | exports: [ConfigService], 794 | }) 795 | class ConfigModule {} 796 | 797 | @Module({ 798 | imports: [ 799 | EthersModule.forRootAsync({ 800 | imports: [ConfigModule], 801 | inject: [ConfigService], 802 | token: 'eth', 803 | useFactory: (config: ConfigService) => { 804 | return { 805 | network: RINKEBY_NETWORK, 806 | pocket: { 807 | applicationId: config.applicationId, 808 | applicationSecretKey: config.applicationSecretKey, 809 | }, 810 | useDefaultProvider: false, 811 | } 812 | }, 813 | }), 814 | EthersModule.forRootAsync({ 815 | imports: [ConfigModule], 816 | inject: [ConfigService], 817 | token: 'poly', 818 | useFactory: (config: ConfigService) => { 819 | return { 820 | network: MUMBAI_NETWORK, 821 | alchemy: config.alchemy, 822 | useDefaultProvider: false, 823 | } 824 | }, 825 | }), 826 | EthersModule.forRootAsync({ 827 | imports: [ConfigModule], 828 | inject: [ConfigService], 829 | token: 'bsc', 830 | useFactory: (config: ConfigService) => { 831 | return { 832 | network: BNB_TESTNET_NETWORK, 833 | custom: config.custom, 834 | useDefaultProvider: false, 835 | } 836 | }, 837 | }), 838 | ], 839 | controllers: [TestController], 840 | }) 841 | class TestModule {} 842 | ``` 843 | 844 | ## Testing a class that uses InjectEthersProvider 845 | 846 | This package exposes a getEthersToken(token?: string) function that returns a prepared injection token based on the provided context. 847 | Using this token, you can easily provide a mock implementation of the `BaseProvider` using any of the standard custom provider techniques, including useClass, useValue, and useFactory. 848 | 849 | ```ts 850 | const module: TestingModule = await Test.createTestingModule({ 851 | providers: [ 852 | MyService, 853 | { 854 | provide: getEthersToken(MyService.name), 855 | useValue: mockProvider, 856 | }, 857 | ], 858 | }).compile(); 859 | ``` 860 | 861 | ## Testing a class that uses InjectContractProvider 862 | 863 | This package exposes a getContractToken(token?: string) function that returns a prepared injection token based on the contract provided context. 864 | Using this token, you can easily provide a mock implementation of the `ethers.Contract` using any of the standard custom provider techniques, including useClass, useValue, and useFactory. 865 | 866 | ```ts 867 | const module: TestingModule = await Test.createTestingModule({ 868 | providers: [ 869 | MyService, 870 | { 871 | provide: getContractToken(MyService.name), 872 | useValue: mockContractProvider, 873 | }, 874 | ], 875 | }).compile(); 876 | ``` 877 | 878 | ## Testing a class that uses InjectSignerProvider 879 | 880 | This package exposes a getSignerToken(token?: string) function that returns a prepared injection token based on the signer provided context. 881 | Using this token, you can easily provide a mock implementation of the `ethers.Signer` using any of the standard custom provider techniques, including useClass, useValue, and useFactory. 882 | 883 | ```ts 884 | const module: TestingModule = await Test.createTestingModule({ 885 | providers: [ 886 | MyService, 887 | { 888 | provide: getSignerToken(MyService.name), 889 | useValue: mockSignerProvider, 890 | }, 891 | ], 892 | }).compile(); 893 | ``` 894 | 895 | ## Migration 896 | 897 | ### v1 898 | 899 | - `SmartContract` was renamed to `Contract` 900 | - `EthersBaseProvider` was renamed to `BaseProvider` 901 | - `SmartContractInterface` was renamed to `ContractInterface` 902 | - `WalletSigner` was renamed to `Wallet` 903 | - `SmartContractFactory` was renamed to `ContractFactory` 904 | - `RandomWalletSignerOptions` was renamed to `RandomWalletOptions` 905 | 906 | A new more convenient way to inject the `EthersSigner` and `EthersContract` providers into a service or controller was add it. 907 | 908 | #### EthersSigner 909 | 910 | ```ts 911 | // v0 912 | import { EthersSigner, WalletSigner } from 'nestjs-ethers'; 913 | 914 | @Injectable() 915 | export class TestService { 916 | constructor(private readonly ethersSigner: EthersSigner) {} 917 | async someMethod(): Promise { 918 | const wallet: WalletSigner = this.ethersSigner.createWallet( 919 | '0x4c94faa2c558a998d10ee8b2b9b8eb1fbcb8a6ac5fd085c6f95535604fc1bffb' 920 | ); 921 | 922 | return wallet.getAddress(); 923 | } 924 | } 925 | 926 | // v1 927 | import { EthersSigner, InjectSignerProvider, Wallet } from 'nestjs-ethers'; 928 | 929 | @Injectable() 930 | export class TestService { 931 | constructor( 932 | @InjectSignerProvider() 933 | private readonly ethersSigner: EthersSigner, 934 | ) {} 935 | async someMethod(): Promise { 936 | const wallet: Wallet = this.ethersSigner 937 | .createWallet( 938 | '0x4c94faa2c558a998d10ee8b2b9b8eb1fbcb8a6ac5fd085c6f95535604fc1bffb' 939 | ); 940 | 941 | return wallet.getAddress(); 942 | } 943 | } 944 | ``` 945 | 946 | #### EthersContract 947 | 948 | ```ts 949 | // v0 950 | import { EthersContract, SmartContract } from 'nestjs-ethers'; 951 | import * as ABI from './utils/ABI.json'; 952 | 953 | @Injectable() 954 | class TestService { 955 | constructor(private readonly ethersContract: EthersContract) {} 956 | async someMethod(): Promise { 957 | const contract: SmartContract = this.ethersContract.create( 958 | '0x012363d61bdc53d0290a0f25e9c89f8257550fb8', 959 | ABI, 960 | ); 961 | 962 | return contract.provider.getNetwork(); 963 | } 964 | } 965 | 966 | // v1 967 | import { EthersContract, InjectContractProvider, Contract, Network } from 'nestjs-ethers'; 968 | import * as ABI from './utils/ABI.json'; 969 | 970 | @Injectable() 971 | class TestService { 972 | constructor( 973 | @InjectContractProvider() 974 | private readonly contract: EthersContract, 975 | ) {} 976 | async someMethod(): Promise { 977 | const contract: Contract = this.ethersContract.create( 978 | '0x012363d61bdc53d0290a0f25e9c89f8257550fb8', 979 | ABI, 980 | ); 981 | 982 | return contract.provider.getNetwork(); 983 | } 984 | } 985 | ``` 986 | 987 | ### v3 988 | 989 | - Migrated to ethers.js v6 from v5, introduced breaking changes, see the [migration guide](https://docs.ethers.org/v6/migrating/#migrating) for comprehensive list of changes 990 | - `BigNumber` was replaced with the standard `bigint` 991 | - `StaticJsonRpcProvider` was merged to `JsonRpcProvider` with `staticNetwork` option. 992 | 993 | ## Change Log 994 | 995 | See [Changelog](CHANGELOG.md) for more information. 996 | 997 | ## Contributing 998 | 999 | Contributions welcome! See [Contributing](CONTRIBUTING.md). 1000 | 1001 | ## Collaborators 1002 | 1003 | * [__Jose Ramirez__](https://github.com/0xslipk) 1004 | 1005 | ## License 1006 | 1007 | Licensed under the Apache 2.0 - see the [LICENSE](LICENSE) file for details. 1008 | --------------------------------------------------------------------------------