├── .github └── workflows │ └── codeql.yml ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── SECURITY.md ├── build_helper └── npm.export.js ├── examples ├── .env.example ├── config.js ├── metamask │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── index.html │ │ └── index.js │ └── webpack.config.js ├── node.js ├── package-lock.json └── package.json ├── package-lock.json ├── package.json ├── src ├── helpers │ ├── do_nothing.ts │ ├── index.ts │ └── transaction_write_result.ts ├── index.ts ├── tsconfig.json ├── utils │ ├── index.ts │ ├── matic_big_number.ts │ ├── matic_tx_config_to_web3.ts │ ├── web3_receipt_to_matic_receipt.ts │ └── web3_tx_to_matic_tx.ts └── web3 │ ├── eth_contract.ts │ ├── eth_method.ts │ ├── index.ts │ └── web3_client.ts ├── test ├── config.js ├── debug.js ├── index.html ├── install_lib.js ├── karma.conf.js ├── package-lock.json ├── package.json ├── specs │ ├── client.ts │ ├── erc20.spec.ts │ ├── hex.spec.ts │ ├── index.ts │ └── pos_bridge.ts ├── tsconfig.json └── webpack.config.test.js ├── tslint.json └── webpack ├── licence.js ├── webpack.base.config.js └── webpack.node.config.js /.github/workflows/codeql.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: '25 4 * * 6' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || '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: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Use only 'java' to analyze code written in Java, Kotlin or both 38 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both 39 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 40 | 41 | steps: 42 | - name: Checkout repository 43 | uses: actions/checkout@v3 44 | 45 | # Initializes the CodeQL tools for scanning. 46 | - name: Initialize CodeQL 47 | uses: github/codeql-action/init@v2 48 | with: 49 | languages: ${{ matrix.language }} 50 | # If you wish to specify custom queries, you can do so here or in a config file. 51 | # By default, queries listed here will override any specified in a config file. 52 | # Prefix the list here with "+" to use these queries and those in the config file. 53 | 54 | # For more 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 55 | # queries: security-extended,security-and-quality 56 | 57 | 58 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). 59 | # If this step fails, then you should remove it and run the build manually (see below) 60 | - name: Autobuild 61 | uses: github/codeql-action/autobuild@v2 62 | 63 | # ℹ️ Command-line programs to run using the OS shell. 64 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 65 | 66 | # If the Autobuild fails above, remove it and uncomment the following three lines. 67 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 68 | 69 | # - run: | 70 | # echo "Run, Build Application using script" 71 | # ./location_of_script_within_repo/buildscript.sh 72 | 73 | - name: Perform CodeQL Analysis 74 | uses: github/codeql-action/analyze@v2 75 | with: 76 | category: "/language:${{matrix.language}}" 77 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | *.env 4 | *.tgz 5 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build_helper 3 | webpack 4 | src 5 | test 6 | 7 | *.tgz 8 | *.env 9 | examples 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Polygon (previously Matic) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/@maticnetwork%2Fmaticjs-web3.svg)](https://badge.fury.io/js/@maticnetwork%2Fmaticjs-web3) 2 | # maticjs-web3 3 | 4 | [web3.js](https://web3js.readthedocs.io/) plugin for matic.js 5 | 6 | # Installation 7 | 8 | ``` 9 | npm i @maticnetwork/maticjs-web3 10 | ``` 11 | 12 | # Examples 13 | 14 | All the examples are in the examples folder. 15 | 16 | # Docs 17 | 18 | ``` 19 | 20 | import { use } from '@maticnetwork/maticjs' 21 | import { Web3ClientPlugin } from '@maticnetwork/maticjs-web3' 22 | 23 | // install ethers plugin 24 | use(Web3ClientPlugin) 25 | ``` 26 | 27 | That's all you need to do and `web3.js` will be used for web3 calls. 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Polygon Technology Security Information 2 | 3 | ## Link to vulnerability disclosure details (Bug Bounty). 4 | - Websites and Applications: https://hackerone.com/polygon-technology 5 | - Smart Contracts: https://immunefi.com/bounty/polygon 6 | 7 | ## Languages that our team speaks and understands. 8 | Preferred-Languages: en 9 | 10 | ## Security-related job openings at Polygon. 11 | https://polygon.technology/careers 12 | 13 | ## Polygon security contact details. 14 | security@polygon.technology 15 | 16 | ## The URL for accessing the security.txt file. 17 | Canonical: https://polygon.technology/security.txt 18 | -------------------------------------------------------------------------------- /build_helper/npm.export.js: -------------------------------------------------------------------------------- 1 | if (process.env.NODE_ENV === 'production') { 2 | module.exports = require('./matic-web3.node.min.js') 3 | } else { 4 | module.exports = require('./matic-web3.node.js') 5 | } 6 | -------------------------------------------------------------------------------- /examples/.env.example: -------------------------------------------------------------------------------- 1 | USER1_PRIVATE_KEY = 2 | USER1_FROM = 3 | ROOT_RPC = 4 | MATIC_RPC = 5 | USER2_PRIVATE_KEY = 6 | USER2_FROM = 7 | -------------------------------------------------------------------------------- /examples/config.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | module.exports = { 4 | rpc: { 5 | root: process.env.ROOT_RPC, 6 | child: process.env.MATIC_RPC || 'https://rpc-mumbai.matic.today' 7 | }, 8 | pos: { 9 | parent: { 10 | erc20: '0x655f2166b0709cd575202630952d71e2bb0d61af', 11 | erc721: '0x16F7EF3774c59264C46E5063b1111bCFd6e7A72f', 12 | erc1155: '0x2e3Ef7931F2d0e4a7da3dea950FF3F19269d9063', 13 | }, 14 | child: { 15 | erc721: '0xbD88C3A7c0e242156a46Fbdf87141Aa6D0c0c649', 16 | erc20: '0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1', 17 | weth: '0x714550C2C1Ea08688607D86ed8EeF4f5E4F22323', 18 | erc1155: '0xA07e45A987F19E25176c877d98388878622623FA', 19 | }, 20 | }, 21 | user1: { 22 | // '' - A sample private key prefix with `0x` 23 | privateKey: process.env.USER1_PRIVATE_KEY, 24 | //'', Your address 25 | address: process.env.USER1_FROM 26 | }, 27 | user2: { 28 | address: process.env.USER2_FROM 29 | }, 30 | proofApi: process.env.PROOF_API 31 | } 32 | -------------------------------------------------------------------------------- /examples/metamask/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "metamask", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "dev": "webpack-dev-server --config webpack.config.js", 9 | "start": "npm run dev" 10 | }, 11 | "author": "", 12 | "license": "ISC", 13 | "devDependencies": { 14 | "css-loader": "^0.28.11", 15 | "file-loader": "^6.2.0", 16 | "html-webpack-plugin": "^3.2.0", 17 | "ts-loader": "^4.1.0", 18 | "typescript": "^2.7.2", 19 | "webpack": "^4.32.2", 20 | "webpack-cli": "^3.3.2", 21 | "webpack-dev-server": "^3.4.1" 22 | }, 23 | "dependencies": {} 24 | } 25 | -------------------------------------------------------------------------------- /examples/metamask/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |
11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/metamask/src/index.js: -------------------------------------------------------------------------------- 1 | import { POSClient, use } from "@maticnetwork/maticjs"; 2 | import { Web3ClientPlugin } from "@maticnetwork/maticjs-web3"; 3 | import Web3 from "web3"; 4 | 5 | import { pos } from "../../config"; 6 | 7 | use(Web3ClientPlugin); 8 | const posClient = new POSClient(); 9 | 10 | window.onload = () => { 11 | document.querySelector('#btnConnect').addEventListener('click', async () => { 12 | if (!window.ethereum) { 13 | return alert("Metamask not installed or not enabled"); 14 | } 15 | await window.ethereum.send('eth_requestAccounts'); 16 | 17 | const from = window.ethereum.selectedAddress; 18 | 19 | const web3 = new Web3(window.ethereum); 20 | 21 | const chainId = await web3.eth.getChainId(); 22 | 23 | // if network is goerli, then it is parent 24 | const isParent = chainId === 5; 25 | 26 | 27 | await posClient.init({ 28 | log: true, 29 | network: "testnet", 30 | version: 'mumbai', 31 | parent: { 32 | provider: web3.currentProvider, 33 | defaultConfig: { 34 | from: from 35 | } 36 | }, 37 | child: { 38 | provider: web3.currentProvider, 39 | defaultConfig: { 40 | from: from 41 | } 42 | } 43 | }); 44 | 45 | const tokenAddress = isParent ? pos.parent.erc20 : pos.child.erc20; 46 | 47 | const erc20Token = posClient.erc20( 48 | tokenAddress 49 | , isParent 50 | ) 51 | 52 | const balance = await erc20Token.getBalance(from); 53 | 54 | console.log("balance", balance); 55 | 56 | alert(`your balance is ${balance}`); 57 | }) 58 | } 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /examples/metamask/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const HtmlWebPackPlugin = require('html-webpack-plugin'); 3 | module.exports = { 4 | entry: './src/index.js', 5 | devtool: 'inline-source-map', 6 | module: { 7 | rules: [{ 8 | test: /\.css?$/, 9 | use: 'css-loader', 10 | exclude: /node_modules/ 11 | }] 12 | }, 13 | resolve: { 14 | extensions: ['.tsx', '.ts', '.js', '.css'] 15 | }, 16 | output: { 17 | filename: 'bundle.js', 18 | path: path.resolve(__dirname, 'bin/') 19 | }, 20 | plugins: [ 21 | new HtmlWebPackPlugin({ 22 | cache: true, 23 | hash: true, 24 | template: './src/index.html', 25 | minify: { 26 | collapseWhitespace: true, 27 | removeComments: true, 28 | removeRedundantAttributes: true, 29 | removeScriptTypeAttributes: true, 30 | removeStyleLinkTypeAttributes: true 31 | } 32 | }) 33 | ] 34 | }; 35 | -------------------------------------------------------------------------------- /examples/node.js: -------------------------------------------------------------------------------- 1 | const { use, POSClient } = require("@maticnetwork/maticjs"); 2 | const { Web3ClientPlugin } = require("@maticnetwork/maticjs-web3"); 3 | const HDWalletProvider = require("@truffle/hdwallet-provider"); 4 | 5 | const dotenv = require('dotenv'); 6 | const path = require('path'); 7 | const env = dotenv.config({ 8 | path: path.join(__dirname, '.env') 9 | }); 10 | 11 | const { user1, rpc, pos } = require("./config"); 12 | 13 | use(Web3ClientPlugin); 14 | 15 | const from = user1.address; 16 | const privateKey = user1.privateKey; 17 | 18 | const execute = async () => { 19 | 20 | const matic = new POSClient(); 21 | await matic.init({ 22 | // log: true, 23 | network: 'testnet', 24 | version: 'mumbai', 25 | parent: { 26 | provider: new HDWalletProvider(privateKey, rpc.root), 27 | defaultConfig: { 28 | from 29 | } 30 | }, 31 | child: { 32 | provider: new HDWalletProvider(privateKey, rpc.child), 33 | defaultConfig: { 34 | from 35 | } 36 | } 37 | }); 38 | 39 | const rootTokenErc20 = matic.erc20(pos.parent.erc20, true); 40 | 41 | const balanceRoot = await rootTokenErc20.getBalance(from) 42 | console.log('balanceRoot', balanceRoot); 43 | } 44 | 45 | execute().then(_ => { 46 | process.exit(0) 47 | }).catch(err => { 48 | console.error("error", err); 49 | process.exit(0); 50 | }) 51 | -------------------------------------------------------------------------------- /examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "examples", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "node.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "@maticnetwork/maticjs": "^3.0.0", 13 | "@maticnetwork/maticjs-web3": "^1.0.0", 14 | "@truffle/hdwallet-provider": "^1.5.1-alpha.1", 15 | "dotenv": "^10.0.0" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@maticnetwork/maticjs-web3", 3 | "version": "1.0.5", 4 | "description": "web3.js plugin for matic.js", 5 | "main": "dist/npm.export.js", 6 | "types": "dist/ts/index.d.ts", 7 | "scripts": { 8 | "build": "npm run build:dev", 9 | "build:link": "npm run build && npm link", 10 | "build:webpack": "npm run lint && webpack --config webpack/webpack.node.config.js", 11 | "build:pack": "npm run build:dev && npm pack", 12 | "build:dev": "cross-env NODE_ENV=development npm run build:webpack", 13 | "build:prod": "cross-env NODE_ENV=production npm run build:webpack", 14 | "deploy": "npm run build:dev && npm run build:prod", 15 | "prepublishOnly": "npm run deploy", 16 | "lint": "tslint src/**/*.ts", 17 | "lint:fix": "tslint src/**/*.ts --fix", 18 | "test": "npm run build:pack && cd test && npm run install:lib:test", 19 | "debug": "npm run build:pack && cd test && npm run install:lib:debug" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/maticnetwork/maticjs-web3.git" 24 | }, 25 | "author": "", 26 | "license": "MIT", 27 | "bugs": { 28 | "url": "https://github.com/maticnetwork/maticjs-web3/issues" 29 | }, 30 | "homepage": "https://github.com/maticnetwork/maticjs-web3#readme", 31 | "dependencies": { 32 | "web3": "^1.8.0" 33 | }, 34 | "peerDependencies": { 35 | "@maticnetwork/maticjs": "^3.2.0" 36 | }, 37 | "devDependencies": { 38 | "@maticnetwork/maticjs": "^3.5.0", 39 | "@types/web3": "1.0.19", 40 | "copy-webpack-plugin": "^6.1.1", 41 | "cross-env": "^7.0.3", 42 | "smart-banner-webpack-plugin": "^3.0.1", 43 | "ts-loader": "^7.0.1", 44 | "tslint": "^6.1.3", 45 | "typescript": "^4.4.2", 46 | "webpack": "^4.43.0", 47 | "webpack-cli": "^4.2.0", 48 | "webpack-merge": "^4.2.2" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/helpers/do_nothing.ts: -------------------------------------------------------------------------------- 1 | export const doNothing = () => { 2 | 3 | }; -------------------------------------------------------------------------------- /src/helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./do_nothing"; 2 | export * from "./transaction_write_result"; -------------------------------------------------------------------------------- /src/helpers/transaction_write_result.ts: -------------------------------------------------------------------------------- 1 | import { ITransactionWriteResult } from "@maticnetwork/maticjs"; 2 | import { web3ReceiptToMaticReceipt } from "../utils"; 3 | import { doNothing } from "./do_nothing"; 4 | 5 | export class TransactionWriteResult implements ITransactionWriteResult { 6 | 7 | onTransactionHash: Function; 8 | onTransactionError: Function; 9 | onTransactionReceiptError: Function; 10 | 11 | onTransactionReceipt: Function; 12 | 13 | getReceipt; 14 | getTransactionHash; 15 | 16 | constructor(private promise: any) { 17 | const receiptPromise = new Promise((res, rej) => { 18 | this.onTransactionReceipt = res; 19 | this.onTransactionReceiptError = rej; 20 | }); 21 | this.getReceipt = () => { 22 | return receiptPromise.then(receipt => { 23 | return web3ReceiptToMaticReceipt(receipt); 24 | }); 25 | }; 26 | 27 | const txHashPromise = new Promise((res, rej) => { 28 | this.onTransactionHash = res; 29 | this.onTransactionError = rej; 30 | }); 31 | 32 | this.getTransactionHash = () => { 33 | return txHashPromise; 34 | }; 35 | 36 | promise.once("transactionHash", this.onTransactionHash). 37 | once("receipt", this.onTransactionReceipt as any). 38 | on("error", this.onTransactionError). 39 | on("error", this.onTransactionReceiptError); 40 | } 41 | 42 | 43 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { IPlugin } from "@maticnetwork/maticjs"; 2 | import Web3 from "web3"; 3 | import { MaticBigNumber } from "./utils"; 4 | import { Web3Client } from "./web3"; 5 | 6 | export class Web3ClientPlugin implements IPlugin { 7 | setup(matic) { 8 | matic.utils.Web3Client = Web3Client; 9 | matic.utils.BN = MaticBigNumber; 10 | matic.utils.isBN = (value) => { 11 | return Web3.utils.isBN(value); 12 | }; 13 | } 14 | } 15 | 16 | export * from "./utils"; 17 | 18 | /* tslint:disable-next-line */ 19 | export default Web3ClientPlugin; -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noImplicitAny": false, 4 | "noEmitOnError": false, 5 | "removeComments": false, 6 | "sourceMap": true, 7 | "inlineSources": true, 8 | "target": "es5", 9 | "preserveConstEnums": true, 10 | "declaration": true, 11 | "module": "ESNext", 12 | "outDir": "../dist/ts", 13 | "lib": [ 14 | "es2015", 15 | "dom", 16 | "webworker", 17 | "ES5", 18 | "ES6" 19 | ], 20 | "moduleResolution": "node", 21 | "allowSyntheticDefaultImports": true, 22 | "skipLibCheck": true 23 | }, 24 | "include": [ 25 | "../src/**/*" 26 | ], 27 | "exclude": [ 28 | "node_namespaces", 29 | "output" 30 | ] 31 | } -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./matic_big_number"; 2 | export * from "./matic_tx_config_to_web3"; 3 | export * from "./web3_receipt_to_matic_receipt"; 4 | export * from "./web3_tx_to_matic_tx"; -------------------------------------------------------------------------------- /src/utils/matic_big_number.ts: -------------------------------------------------------------------------------- 1 | import { BaseBigNumber } from "@maticnetwork/maticjs"; 2 | import BN from "bn.js"; 3 | import Web3 from "web3"; 4 | 5 | export class MaticBigNumber extends BaseBigNumber { 6 | private bn_: BN; 7 | 8 | constructor(value) { 9 | super(); 10 | this.bn_ = new BN(value); 11 | 12 | // this.bn_.toString() 13 | } 14 | 15 | static isBN(value) { 16 | if (value instanceof MaticBigNumber) { 17 | return true; 18 | } 19 | return BN.isBN(value); 20 | } 21 | 22 | toString(base?) { 23 | return this.bn_.toString(base); 24 | } 25 | 26 | toNumber() { 27 | return this.bn_.toNumber(); 28 | } 29 | 30 | toBuffer(base?) { 31 | return this.bn_.toBuffer(); 32 | } 33 | 34 | // static from(value) { 35 | // return new MaticBigNumber(value); 36 | // } 37 | 38 | add(value: BaseBigNumber) { 39 | const bn = this.bn_.add( 40 | new BN(value.toString()) 41 | ); 42 | return new MaticBigNumber(bn); 43 | } 44 | 45 | sub(value: BaseBigNumber) { 46 | const bn = this.bn_.sub( 47 | new BN(value.toString()) 48 | ); 49 | return new MaticBigNumber(bn); 50 | } 51 | 52 | mul(value: BaseBigNumber) { 53 | const bn = this.bn_.mul( 54 | new BN(value.toString()) 55 | ); 56 | return new MaticBigNumber(bn); 57 | } 58 | 59 | div(value: BaseBigNumber) { 60 | const bn = this.bn_.div( 61 | new BN(value.toString()) 62 | ); 63 | return new MaticBigNumber(bn); 64 | } 65 | 66 | lte(value: BaseBigNumber) { 67 | return this.bn_.lte( 68 | new BN(value.toString()) 69 | ); 70 | } 71 | 72 | lt(value: BaseBigNumber) { 73 | return this.bn_.lt( 74 | new BN(value.toString()) 75 | ); 76 | } 77 | 78 | gte(value: BaseBigNumber) { 79 | return this.bn_.gte( 80 | new BN(value.toString()) 81 | ); 82 | } 83 | 84 | gt(value: BaseBigNumber) { 85 | return this.bn_.gt( 86 | new BN(value.toString()) 87 | ); 88 | } 89 | 90 | eq(value: BaseBigNumber) { 91 | return this.bn_.eq( 92 | new BN(value.toString()) 93 | ); 94 | } 95 | } -------------------------------------------------------------------------------- /src/utils/matic_tx_config_to_web3.ts: -------------------------------------------------------------------------------- 1 | import { ITransactionRequestConfig } from "@maticnetwork/maticjs"; 2 | import Web3 from "web3"; 3 | import { TransactionConfig } from "web3-core"; 4 | 5 | export const maticTxRequestConfigToWeb3 = (config: ITransactionRequestConfig = {}) => { 6 | const toHex = Web3.utils.toHex; 7 | return { 8 | chainId: toHex(config.chainId) as any, 9 | data: config.data, 10 | from: config.from, 11 | gas: config.gasLimit, 12 | gasPrice: config.gasPrice, 13 | nonce: config.nonce, 14 | to: config.to, 15 | value: config.value, 16 | maxFeePerGas: config.maxFeePerGas, 17 | maxPriorityFeePerGas: config.maxPriorityFeePerGas, 18 | type: toHex(config.type), 19 | hardfork: config.hardfork 20 | } as TransactionConfig; 21 | }; -------------------------------------------------------------------------------- /src/utils/web3_receipt_to_matic_receipt.ts: -------------------------------------------------------------------------------- 1 | import { ITransactionReceipt } from "@maticnetwork/maticjs"; 2 | 3 | 4 | export const web3ReceiptToMaticReceipt = (receipt: any) => { 5 | return { 6 | blockHash: receipt.blockHash, 7 | blockNumber: receipt.blockNumber, 8 | contractAddress: receipt.contractAddress, 9 | cumulativeGasUsed: receipt.cumulativeGasUsed, 10 | from: receipt.from, 11 | gasUsed: receipt.gasUsed, 12 | status: receipt.status, 13 | to: receipt.to, 14 | transactionHash: receipt.transactionHash, 15 | transactionIndex: receipt.transactionIndex, 16 | events: receipt.events, 17 | logs: receipt.logs, 18 | logsBloom: receipt.logsBloom, 19 | root: (receipt as any).root, 20 | type: (receipt as any).type 21 | } as ITransactionReceipt; 22 | 23 | }; -------------------------------------------------------------------------------- /src/utils/web3_tx_to_matic_tx.ts: -------------------------------------------------------------------------------- 1 | import { ITransactionData } from "@maticnetwork/maticjs"; 2 | import { Transaction } from "web3/eth/types"; 3 | 4 | export const web3TxToMaticTx = (tx: Transaction) => { 5 | const maticTx: ITransactionData = tx as any; 6 | maticTx.transactionHash = tx.hash; 7 | return maticTx; 8 | }; -------------------------------------------------------------------------------- /src/web3/eth_contract.ts: -------------------------------------------------------------------------------- 1 | import { BaseContract } from "@maticnetwork/maticjs"; 2 | import Contract from "web3/eth/contract"; 3 | import { EthMethod } from "./eth_method"; 4 | 5 | export class Web3Contract extends BaseContract { 6 | contract: Contract; 7 | 8 | constructor(address: string, contract: Contract, logger) { 9 | super(address, logger); 10 | this.contract = contract; 11 | } 12 | 13 | method(methodName: string, ...args) { 14 | this.logger.log("methodName", methodName, "args method", arguments); 15 | return new EthMethod( 16 | this.address, this.logger, this.contract.methods[methodName](...args) 17 | ); 18 | } 19 | } -------------------------------------------------------------------------------- /src/web3/eth_method.ts: -------------------------------------------------------------------------------- 1 | import { BaseContractMethod, Logger, ITransactionRequestConfig, Converter } from "@maticnetwork/maticjs"; 2 | import Web3 from "web3"; 3 | import { TransactionObject, Tx } from "web3/eth/types"; 4 | import { doNothing, TransactionWriteResult } from "../helpers"; 5 | import { maticTxRequestConfigToWeb3 } from "../utils"; 6 | 7 | export class EthMethod extends BaseContractMethod { 8 | 9 | constructor(public address, logger: Logger, private method: TransactionObject) { 10 | super(logger); 11 | } 12 | 13 | toHex(value) { 14 | return value != null ? Web3.utils.toHex(value) : value; 15 | } 16 | 17 | read(tx: ITransactionRequestConfig, defaultBlock?: number | string): Promise { 18 | this.logger.log("sending tx with config", tx, defaultBlock); 19 | return (this.method.call as any)( 20 | maticTxRequestConfigToWeb3(tx) as any, defaultBlock 21 | ); 22 | } 23 | 24 | write(tx: ITransactionRequestConfig) { 25 | 26 | return new TransactionWriteResult( 27 | this.method.send( 28 | maticTxRequestConfigToWeb3(tx) as any 29 | ) 30 | ); 31 | } 32 | 33 | estimateGas(tx: ITransactionRequestConfig): Promise { 34 | return this.method.estimateGas( 35 | maticTxRequestConfigToWeb3(tx) as any 36 | ); 37 | } 38 | 39 | encodeABI() { 40 | return this.method.encodeABI(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/web3/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./web3_client"; 2 | export * from "./eth_method"; -------------------------------------------------------------------------------- /src/web3/web3_client.ts: -------------------------------------------------------------------------------- 1 | import { Web3Contract } from "./eth_contract"; 2 | import Web3 from "web3"; 3 | import { Transaction } from "web3/eth/types"; 4 | import { AbstractProvider } from "web3-core"; 5 | import { doNothing, TransactionWriteResult } from "../helpers"; 6 | import { BaseWeb3Client, IBlockWithTransaction, IJsonRpcRequestPayload, IJsonRpcResponse, ITransactionRequestConfig, ITransactionData, ITransactionReceipt, Logger, ERROR_TYPE, IError } from "@maticnetwork/maticjs"; 7 | import { maticTxRequestConfigToWeb3, web3ReceiptToMaticReceipt, web3TxToMaticTx } from "../utils"; 8 | 9 | export class Web3Client extends BaseWeb3Client { 10 | private web3_: Web3; 11 | name = 'WEB3'; 12 | 13 | constructor(provider: any, logger: Logger) { 14 | super(logger); 15 | this.web3_ = new Web3(provider); 16 | } 17 | 18 | 19 | read(config: ITransactionRequestConfig) { 20 | return this.web3_.eth.call( 21 | maticTxRequestConfigToWeb3(config) 22 | ); 23 | } 24 | 25 | write(config: ITransactionRequestConfig) { 26 | return new TransactionWriteResult( 27 | this.web3_.eth.sendTransaction( 28 | maticTxRequestConfigToWeb3(config) 29 | ) 30 | ); 31 | } 32 | 33 | getContract(address: string, abi: any) { 34 | const cont = new this.web3_.eth.Contract(abi, address); 35 | return new Web3Contract(address, cont as any, this.logger); 36 | } 37 | 38 | getGasPrice() { 39 | return this.web3_.eth.getGasPrice(); 40 | } 41 | 42 | estimateGas(config: ITransactionRequestConfig) { 43 | return this.web3_.eth.estimateGas( 44 | maticTxRequestConfigToWeb3(config) 45 | ); 46 | } 47 | 48 | getTransactionCount(address: string, blockNumber: any) { 49 | return this.web3_.eth.getTransactionCount(address, blockNumber); 50 | } 51 | 52 | getAccounts() { 53 | return this.web3_.eth.getAccounts(); 54 | } 55 | 56 | async getChainId() { 57 | try { 58 | const chainId = await this.web3_.eth.net.getId(); 59 | if (chainId) { 60 | return chainId; 61 | } 62 | throw new Error('net_version is not enabled'); 63 | } catch (e) { 64 | return this.web3_.eth.getChainId(); 65 | } 66 | } 67 | 68 | private ensureTransactionNotNull_(data) { 69 | if (!data) { 70 | throw { 71 | type: 'invalid_transaction' as any, 72 | message: 'Could not retrieve transaction. Either it is invalid or might be in archive node.' 73 | } as IError; 74 | } 75 | } 76 | 77 | getTransaction(transactionHash: string) { 78 | return this.web3_.eth.getTransaction(transactionHash).then(data => { 79 | this.ensureTransactionNotNull_(data); 80 | return web3TxToMaticTx(data); 81 | }); 82 | } 83 | 84 | getTransactionReceipt(transactionHash: string): Promise { 85 | return this.web3_.eth.getTransactionReceipt(transactionHash).then(data => { 86 | this.ensureTransactionNotNull_(data); 87 | return web3ReceiptToMaticReceipt(data); 88 | }); 89 | } 90 | 91 | getBlock(blockHashOrBlockNumber) { 92 | return (this.web3_.eth.getBlock(blockHashOrBlockNumber) as any); 93 | } 94 | 95 | getBalance(address) { 96 | return this.web3_.eth.getBalance(address); 97 | } 98 | 99 | getBlockWithTransaction(blockHashOrBlockNumber) { 100 | return this.web3_.eth.getBlock(blockHashOrBlockNumber, true).then(result => { 101 | const blockData: IBlockWithTransaction = result as any; 102 | blockData.transactions = result.transactions.map(tx => { 103 | return web3TxToMaticTx(tx); 104 | }); 105 | return blockData; 106 | }); 107 | } 108 | 109 | sendRPCRequest(request: IJsonRpcRequestPayload) { 110 | return new Promise((res, rej) => { 111 | (this.web3_.currentProvider as AbstractProvider).send(request, (error, result) => { 112 | if (error) return rej(error); 113 | res(result as any); 114 | }); 115 | }); 116 | } 117 | 118 | signTypedData(signer, typedData) { 119 | return this.sendRPCRequest({ 120 | jsonrpc: '2.0', 121 | method: 'eth_signTypedData_v4', 122 | params: [signer, typedData], 123 | id: new Date().getTime() 124 | }).then(payload => { 125 | return String(payload.result); 126 | }); 127 | } 128 | 129 | encodeParameters(params: any[], types: any[]) { 130 | return this.web3_.eth.abi.encodeParameters(types, params); 131 | } 132 | 133 | decodeParameters(hexString, types: any[]) { 134 | return this.web3_.eth.abi.decodeParameters(types, hexString) as any; 135 | } 136 | 137 | etheriumSha3(...value) { 138 | return Web3.utils.soliditySha3(...value); 139 | } 140 | 141 | hexToNumber(value) { 142 | return Web3.utils.hexToNumber(value); 143 | } 144 | 145 | hexToNumberString(value) { 146 | return Web3.utils.hexToNumberString(value); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /test/config.js: -------------------------------------------------------------------------------- 1 | // const dotenv = require('dotenv'); 2 | // const path = require('path'); 3 | // const env = dotenv.config({ 4 | // path: path.join(__dirname, '.env') 5 | // }); 6 | module.exports = { 7 | rpc: { 8 | parent: process.env.ROOT_RPC, 9 | child: process.env.MATIC_RPC || 'https://rpc-mumbai.matic.today', 10 | }, 11 | pos: { 12 | parent: { 13 | erc20: '0x3f152b63ec5ca5831061b2dccfb29a874c317502', 14 | // erc20: '0x655f2166b0709cd575202630952d71e2bb0d61af', 15 | erc721: '0x5a08d01e07714146747950CE07BB0f741445D1b8', 16 | erc1155: '0x2e3Ef7931F2d0e4a7da3dea950FF3F19269d9063', 17 | chainManagerAddress: '0xBbD7cBFA79faee899Eaf900F13C9065bF03B1A74', // Address of RootChainManager proxy for POS Portal 18 | }, 19 | child: { 20 | erc721: '0xEC8CB8bBb069470bC358ffB0e3710c64830da383', 21 | // erc20: '0xfe4F5145f6e09952a5ba9e956ED0C25e3Fa4c7F1', 22 | erc20: '0xA0D9f8282cD48d22Fd875E43Be32793124f8eD47', 23 | weth: '0x714550C2C1Ea08688607D86ed8EeF4f5E4F22323', 24 | erc1155: '0xA07e45A987F19E25176c877d98388878622623FA', 25 | }, 26 | }, 27 | user1: { 28 | "privateKey": process.env.USER1_PRIVATE_KEY, 29 | "address": process.env.USER1_FROM 30 | }, 31 | user2: { 32 | address: process.env.USER2_FROM, // Your address 33 | "privateKey": process.env.USER2_PRIVATE_KEY 34 | }, 35 | } 36 | -------------------------------------------------------------------------------- /test/debug.js: -------------------------------------------------------------------------------- 1 | const { setProofApi, POSClient, use, Converter, utils } = require("@maticnetwork/maticjs"); 2 | const { Web3ClientPlugin } = require("@maticnetwork/maticjs-web3"); 3 | 4 | const HDWalletProvider = require("@truffle/hdwallet-provider"); 5 | const { user1, rpc, pos } = require("./config"); 6 | use(Web3ClientPlugin); 7 | const from = user1.address; 8 | 9 | const execute = async () => { 10 | 11 | // return console.log(Converter.toHex('10'), new utils.BN('10').toString(16)) 12 | 13 | 14 | const privateKey = user1.privateKey; 15 | const mumbaiERC20 = pos.child.erc20; 16 | const goerliERC20 = pos.parent.erc20; 17 | 18 | const client = new POSClient(); 19 | 20 | 21 | await client.init({ 22 | log: true, 23 | network: 'testnet', 24 | version: 'mumbai', 25 | parent: { 26 | provider: new HDWalletProvider(privateKey, rpc.parent), 27 | defaultConfig: { 28 | from 29 | } 30 | }, 31 | child: { 32 | provider: new HDWalletProvider(privateKey, rpc.child), 33 | defaultConfig: { 34 | from 35 | } 36 | } 37 | }); 38 | console.log("init called"); 39 | 40 | const mumbaiERC20Token = client.erc20(mumbaiERC20); 41 | const goerliERC20Token = client.erc20(goerliERC20, true); 42 | const goerliERC721Token = client.erc721(pos.parent.erc721, true); 43 | const mumbaiERC721Token = client.erc721(pos.child.erc721); 44 | 45 | const txReceipt = await client.client.parent.getTransactionReceipt('0x92898987248eaec73dc56eee44f68084a2adcb13a83213590cce437d54aa17db') 46 | 47 | return console.log(txReceipt) 48 | 49 | // return console.log(await client.isDeposited('0xc67599f5c967f2040786d5924ec55d37bf943c009bdd23f3b50e5ae66efde258')); 50 | 51 | 52 | // const balance = await mumbaiERC20Token.getBalance( 53 | // from 54 | // ); 55 | // return console.log("balance", balance); 56 | 57 | // const tokens = await goerliERC721Token.getAllTokens( 58 | // from 59 | // ); 60 | // return console.log("tokens", tokens); 61 | 62 | const tx = await goerliERC20Token.approveMax({ 63 | // maxPriorityFeePerGas: 2000000000, 64 | // returnTransaction: true 65 | }); 66 | 67 | // const tx = await goerliERC721Token.depositMany(['70362948865848051982628883253610138761681237831617060123833093242173388773544'], from, { 68 | // returnTransaction: true 69 | // }); 70 | // setProofApi("https://apis.matic.network") 71 | // const tx = await goerliERC20Token.withdrawExitFaster( 72 | // '0x1c20c41b9d97d1026aa456a21f13725df63edec1b1f43aacb180ebcc6340a2d3', { 73 | // returnTransaction: true 74 | // }); 75 | 76 | // console.log('tx', tx); 77 | 78 | // const payload = await client.exitUtil.buildPayloadForExit( 79 | // '0x1c20c41b9d97d1026aa456a21f13725df63edec1b1f43aacb180ebcc6340a2d3', 80 | // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 81 | // false 82 | // ) 83 | // return //console.log("payload", payload, "length", payload.length); 84 | 85 | 86 | // // setProofApi("https://apis.matic.network") 87 | // // const tx = await goerliERC20Token.withdrawExit('0xd6f7f4c6052611761946519076de28fbd091693af974e7d4abc1b17fd7926fd7'); 88 | console.log("txHash", await tx.getTransactionHash()); 89 | console.log("txReceipt", await tx.getReceipt()); 90 | 91 | //txhash to plasma exit - 0x63aa095e0d6ee8698399b871daa202eb5522933e2d94c5929cf0fb86b6b0c628 92 | const tokenId = '60399350241383852757821046101235634991156913804166740995010931519407953501076' 93 | 94 | // const tx = await (client['client_']).child.getTransactionCount(from, 'pending'); 95 | // console.log("tx", tx); 96 | // const result = await client.isCheckPointed('0x41162584974896bfc96d91e7ce72009373cd31acabe92024950831ee7b8067c0') 97 | // console.log("result", result); 98 | // const tx = await goerliERC721Token.withdrawChallenge( 99 | // '0x41162584974896bfc96d91e7ce72009373cd31acabe92024950831ee7b8067c0', 100 | // { 101 | // // nonce: 11793, 102 | // // gasPrice: '1000', 103 | // // gas: 10000, 104 | // // returnTransaction: true, 105 | // // gasPrice: '4000000000', 106 | // // returnTransaction: true, 107 | // gasLimit: 1046107, 108 | // } 109 | // ); 110 | // console.log("tx", tx) 111 | // console.log("txHash", await tx.getTransactionHash()); 112 | // console.log("txReceipt", await tx.getReceipt()); 113 | } 114 | 115 | execute().then(_ => { 116 | process.exit(0) 117 | }).catch(err => { 118 | console.error(err); 119 | process.exit(0); 120 | }) 121 | -------------------------------------------------------------------------------- /test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /test/install_lib.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs') 2 | const { execSync } = require('child_process') 3 | const path = require('path') 4 | 5 | const content = readFileSync('../package.json') 6 | 7 | const packageInfo = JSON.parse(content) 8 | 9 | if (packageInfo) { 10 | const version = packageInfo.version 11 | console.log('version', version) 12 | execSync(`npm i ../maticnetwork-maticjs-web3-${version}.tgz --no-save`) 13 | } else { 14 | throw 'no package found' 15 | } 16 | -------------------------------------------------------------------------------- /test/karma.conf.js: -------------------------------------------------------------------------------- 1 | const webpackConfig = require('./webpack.config.test') 2 | process.env.CHROME_BIN = require('puppeteer').executablePath() 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | frameworks: ['mocha'], 7 | // plugins: ['karma-chai'], 8 | files: [ 9 | // "src/**/*.ts", 10 | 'specs/index.ts', // *.tsx for React Jsx 11 | ], 12 | preprocessors: { 13 | '**/*.ts': 'webpack', 14 | '**/*.js': 'webpack', 15 | }, 16 | webpack: webpackConfig, 17 | client: { 18 | mocha: { 19 | timeout: 60000, 20 | }, 21 | }, 22 | reporters: ['mocha'], 23 | // browsers: ["jsdom"], 24 | colors: true, 25 | logLevel: config.LOG_INFO, 26 | browsers: ['HeadlessChrome'], 27 | customLaunchers: { 28 | HeadlessChrome: { 29 | base: 'ChromeHeadless', 30 | flags: [ 31 | '--no-sandbox', 32 | '--disable-setuid-sandbox', 33 | '--headless', 34 | '--disable-gpu', 35 | '--disable-translate', 36 | '--disable-extensions', 37 | ], 38 | }, 39 | }, 40 | autoWatch: false, 41 | singleRun: true, 42 | concurrency: Infinity, 43 | browserNoActivityTimeout: 40000, 44 | }) 45 | } 46 | -------------------------------------------------------------------------------- /test/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.spec.js", 6 | "scripts": { 7 | "link:lib": "npm link @maticnetwork/maticjs", 8 | "debug": "dotenv node debug.js", 9 | "install:lib": "node install_lib.js", 10 | "install:lib:test": "npm run install:lib && npm run test", 11 | "install:lib:debug": "npm run install:lib && npm run debug", 12 | "un:lib": "npm un @maticnetwork/maticjs", 13 | "karma:start": "dotenv karma start karma.conf.js", 14 | "test": "cross-env NODE_ENV=test npm run karma:start", 15 | "test:all": "cross-env NODE_ENV=test_all npm run karma:start", 16 | "test:mocha": "cross-env-file -p ./config.json cross-env NODE_ENV=test mochapack --webpack-config ./webpack.config.test.js --colors ./specs/index.ts" 17 | }, 18 | "author": "", 19 | "license": "ISC", 20 | "devDependencies": { 21 | "@types/mocha": "^9.0.0", 22 | "chai": "^3.5.0", 23 | "cross-env": "^7.0.3", 24 | "cross-env-file": "^1.0.0", 25 | "dotenv": "^10.0.0", 26 | "dotenv-cli": "^4.0.0", 27 | "karma": "^6.3.2", 28 | "karma-chai": "^0.1.0", 29 | "karma-chrome-launcher": "^3.1.0", 30 | "karma-firefox-launcher": "^1.3.0", 31 | "karma-mocha": "^2.0.1", 32 | "karma-mocha-reporter": "^2.2.5", 33 | "karma-webpack": "^4.0.2", 34 | "mocha": "^8.2.1", 35 | "puppeteer": "^5.5.0", 36 | "webpack-cli": "^4.2.0" 37 | }, 38 | "dependencies": { 39 | "@truffle/hdwallet-provider": "^1.5.1-alpha.1" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/specs/client.ts: -------------------------------------------------------------------------------- 1 | import { POSClient } from "@maticnetwork/maticjs"; 2 | import { user1, rpc, pos, user2 } from "../config"; 3 | 4 | export const privateKey = user1.privateKey; 5 | export const from = user1.address; 6 | export const to = user2.address; 7 | export const toPrivateKey = user2.privateKey; 8 | 9 | export const RPC = rpc; 10 | 11 | export const erc20 = { 12 | parent: pos.parent.erc20, 13 | child: pos.child.erc20 14 | } 15 | export const erc721 = { 16 | parent: pos.parent.erc721, 17 | child: pos.child.erc721 18 | } 19 | 20 | export const posClient = new POSClient(); 21 | 22 | export const posClientForTo = new POSClient(); 23 | -------------------------------------------------------------------------------- /test/specs/erc20.spec.ts: -------------------------------------------------------------------------------- 1 | import { erc20, from, posClient, posClientForTo, to } from "./client"; 2 | import { expect } from 'chai' 3 | import BN from "bn.js"; 4 | import { maticTxRequestConfigToWeb3 } from "@maticnetwork/maticjs-web3"; 5 | import { ITransactionRequestConfig, ABIManager } from "@maticnetwork/maticjs"; 6 | import { Tx } from "web3/eth/types"; 7 | import Web3 from "web3"; 8 | 9 | 10 | describe('ERC20', () => { 11 | 12 | let erc20Child = posClient.erc20(erc20.child); 13 | let erc20Parent = posClient.erc20(erc20.parent, true); 14 | 15 | const abiManager = new ABIManager("testnet", "mumbai"); 16 | before(() => { 17 | return Promise.all([ 18 | abiManager.init() 19 | ]); 20 | }); 21 | 22 | 23 | it('get balance child', async () => { 24 | console.log('process.env.NODE_ENV', process.env.NODE_ENV); 25 | 26 | const balance = await erc20Child.getBalance(from); 27 | console.log('balance', balance); 28 | expect(balance).to.be.an('string'); 29 | expect(Number(balance)).gte(0); 30 | }) 31 | 32 | it('get balance parent', async () => { 33 | const balance = await erc20Parent.getBalance(from); 34 | console.log('balance', balance); 35 | expect(balance).to.be.an('string'); 36 | expect(Number(balance)).gte(0); 37 | }) 38 | 39 | it('get allowance', async () => { 40 | const allowance = await erc20Parent.getAllowance(from); 41 | expect(allowance).to.be.an('string'); 42 | expect(Number(allowance)).gte(0); 43 | }) 44 | 45 | it('is check pointed', async () => { 46 | const isCheckPointed = await posClient.isCheckPointed('0xd6f7f4c6052611761946519076de28fbd091693af974e7d4abc1b17fd7926fd7'); 47 | expect(isCheckPointed).to.be.an('boolean').equal(true); 48 | }) 49 | 50 | it('isWithdrawExited', async () => { 51 | const exitTxHash = '0x95844235073da694e311dc90476c861e187c36f86a863a950534c9ac2b7c1a48'; 52 | const isExited = await erc20Parent.isWithdrawExited('0xd6f7f4c6052611761946519076de28fbd091693af974e7d4abc1b17fd7926fd7'); 53 | expect(isExited).to.be.an('boolean').equal(true); 54 | }) 55 | 56 | it('check for config props', async () => { 57 | const contract = await erc20Parent.getContract(); 58 | const txConfig = { 59 | from: '0xfd71dc9721d9ddcf0480a582927c3dcd42f3064c', 60 | maxPriorityFeePerGas: 2000000000, 61 | chainId: 5, 62 | gasLimit: 26624, 63 | nonce: 2980, 64 | type: 2, 65 | maxFeePerGas: 20, 66 | data: 'ddd', 67 | gasPrice: 12345, 68 | hardfork: 'true', 69 | to: '12233', 70 | value: 1245 71 | } as ITransactionRequestConfig; 72 | 73 | const config = maticTxRequestConfigToWeb3(txConfig); 74 | 75 | const configLength = Object.keys(config).length; 76 | const txConfigLength = Object.keys(txConfig).length; 77 | 78 | // console.log("configLength", config, configLength, 79 | // "txConfigLength", txConfig, txConfigLength); 80 | 81 | expect(configLength).equal( 82 | txConfigLength 83 | ) 84 | 85 | expect(config.from).equal(txConfig.from); 86 | expect(config['maxPriorityFeePerGas']).equal(txConfig.maxPriorityFeePerGas); 87 | expect(config.chainId).equal( 88 | Web3.utils.toHex(txConfig.chainId) 89 | ); 90 | expect(config.gas).equal(txConfig.gasLimit); 91 | expect(config.nonce).equal(txConfig.nonce); 92 | expect(config['type']).equal( 93 | Web3.utils.toHex(txConfig.type) 94 | ); 95 | expect(config['maxFeePerGas']).equal(txConfig.maxFeePerGas); 96 | expect(config.data).equal(txConfig.data); 97 | expect(config.gasPrice).equal(txConfig.gasPrice); 98 | expect(config.hardfork).equal(txConfig.hardfork); 99 | expect(config.to).equal(txConfig.to); 100 | expect(config.value).equal(txConfig.value); 101 | 102 | }) 103 | 104 | it('child transfer returnTransaction with erp1159', async () => { 105 | const amount = 10; 106 | try { 107 | const result = await erc20Child.transfer(amount, to, { 108 | maxFeePerGas: 10, 109 | maxPriorityFeePerGas: 10, 110 | returnTransaction: true 111 | }); 112 | console.log('result', result); 113 | } catch (error) { 114 | console.log('error', error); 115 | expect(error).deep.equal({ 116 | message: `Child chain doesn't support eip-1559`, 117 | type: 'eip-1559_not_supported' 118 | }) 119 | } 120 | }); 121 | 122 | it('child transfer returnTransaction', async () => { 123 | const amount = 10; 124 | const result = await erc20Child.transfer(amount, to, { 125 | returnTransaction: true 126 | }); 127 | console.log('result', result); 128 | expect(result).to.have.not.property('maxFeePerGas') 129 | expect(result).to.have.not.property('maxPriorityFeePerGas') 130 | // expect(result).to.have.property('gasPrice') 131 | expect(result).to.have.property('chainId', 80001); 132 | }); 133 | 134 | it('parent transfer returnTransaction with erp1159', async () => { 135 | const amount = 10; 136 | const result = await erc20Parent.transfer(amount, to, { 137 | maxFeePerGas: 20, 138 | maxPriorityFeePerGas: 20, 139 | returnTransaction: true 140 | }); 141 | console.log('result', result); 142 | 143 | expect(result).to.have.property('maxFeePerGas', 20) 144 | expect(result).to.have.property('maxPriorityFeePerGas', 20) 145 | expect(result).to.have.not.property('gasPrice') 146 | expect(result).to.have.property('chainId', 5); 147 | 148 | }); 149 | 150 | it('isDeposited', async () => { 151 | const txHash = '0xc67599f5c967f2040786d5924ec55d37bf943c009bdd23f3b50e5ae66efde258'; 152 | const isDeposited = await posClient.isDeposited(txHash); 153 | expect(isDeposited).to.be.an('boolean').equal(true); 154 | }) 155 | 156 | it('withdrawstart return tx', async () => { 157 | 158 | const result = await erc20Child.withdrawStart('10', { 159 | returnTransaction: true 160 | }); 161 | 162 | expect(result['to'].toLowerCase()).equal(erc20.child.toLowerCase()); 163 | expect(result).to.have.property('data') 164 | 165 | }); 166 | 167 | it('approve return tx', async () => { 168 | const result = await erc20Parent.approve('10', { 169 | returnTransaction: true 170 | }); 171 | 172 | expect(result['to'].toLowerCase()).equal(erc20.parent.toLowerCase()); 173 | expect(result).to.have.property('data') 174 | 175 | }); 176 | 177 | it('deposit return tx', async () => { 178 | const result = await erc20Parent.deposit(10, from, { 179 | returnTransaction: true 180 | }); 181 | 182 | const rootChainManager = await abiManager.getConfig("Main.POSContracts.RootChainManagerProxy") 183 | expect(result['to'].toLowerCase()).equal(rootChainManager.toLowerCase()); 184 | }); 185 | 186 | // it('build payload for exit', async () => { 187 | 188 | // const payload = await posClient.exitUtil.buildPayloadForExit( 189 | // '0x1c20c41b9d97d1026aa456a21f13725df63edec1b1f43aacb180ebcc6340a2d3', 190 | // '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 191 | // false 192 | // ) 193 | // expect(payload).equal("0xf9082484235e69b0b9010031f7f7ef8848837caca0654cdd16c2c1af23e138d5ea431107325c6d99dfa567b8e395866f4fd177d79de4a8fec9d06ecea4223f55d1724e6c8455dc62148394266f9e732545254f25407139bd8cb3ecfbd9053933f23e1fca181659680cf4c1a5a6c6f723df2d7d35f3fc14929c8ccef3a9fff644db162a845ecf3a89f41b98436f15fada0f112ebea28f29e9e97f3635bd68ff97de3c0f5cdbd867bd8cb13af5930f55ca3b9ee8f345c3923965d2935a72bb4ddff77b6d5a8f427fbe79945d58189e2f58bec6c09e38c058bb80978eee60bcc260c883be329eb37a9c029e7d5733a173b53aeb0e92f925db4dc681d4bfa2f05c8c5fdd296230d1411b05264a84013c786a84617a6c24a0a317bf456e88f02bccaab4c7aa1a919485ee451901772eeff615a2ab305f3ca0a0984131328f0f9b4ffba09638e99ce4ec98b1aec6eb46eb3023078a03be9d51f8b902ebf902e801830743f9b9010000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000008000000800000000000000000000100000000000000000000020000000000000000000800000000000000000080000010000000000000000000010000000008000000000000000000000000000000000000000000200000000000000020000000000000010001000000000000000000000000004000000003000000000001000000000000000000000000000000100000400020000000000000000000000000000000000000000000000000000000000000100000f901ddf89b94fe4f5145f6e09952a5ba9e956ed0c25e3fa4c7f1f863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca00000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000af9013d940000000000000000000000000000000000001010f884a04dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63a00000000000000000000000000000000000000000000000000000000000001010a0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca0000000000000000000000000c26880a0af2ea0c7e8130e6ec47af756465452e8b8a000000000000000000000000000000000000000000000000000005d17d8a0120000000000000000000000000000000000000000000000006f680513d061bb0d020000000000000000000000000000000000000000000001c57a98b6c5d67d41f500000000000000000000000000000000000000000000006f6804b6b8891afb020000000000000000000000000000000000000000000001c57a9913ddaf1d53f5b903dbf903d8f851a051de183267eca4127869bd2deab74a212d98ec445ea022f108006a65d32011b780808080808080a0f3099598ea2f187f803b8d66b328edf300720bfb016f4d89b4a1eceebf969f508080808080808080f89180a0ee5f307c063eefc1f9ad442f3b9f8f2981f9385b41da5465de5ac5dec863d5c7a0d5a8f8f4ab278e0aea28f1044da97c7bd3a5e807b48cd01bf705b704aa5ddd14a032a40b81b5316142b455addcb7bdd194be8e38196408efefcc4291803a402eeea0188088651f1f064c8fa57051108a83c9d695f1a124dc3783ed2a2e6e7c8fd21a808080808080808080808080f902ef20b902ebf902e801830743f9b9010000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000008000000800000000000000000000100000000000000000000020000000000000000000800000000000000000080000010000000000000000000010000000008000000000000000000000000000000000000000000200000000000000020000000000000010001000000000000000000000000004000000003000000000001000000000000000000000000000000100000400020000000000000000000000000000000000000000000000000000000000000100000f901ddf89b94fe4f5145f6e09952a5ba9e956ed0c25e3fa4c7f1f863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca00000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000af9013d940000000000000000000000000000000000001010f884a04dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63a00000000000000000000000000000000000000000000000000000000000001010a0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca0000000000000000000000000c26880a0af2ea0c7e8130e6ec47af756465452e8b8a000000000000000000000000000000000000000000000000000005d17d8a0120000000000000000000000000000000000000000000000006f680513d061bb0d020000000000000000000000000000000000000000000001c57a98b6c5d67d41f500000000000000000000000000000000000000000000006f6804b6b8891afb020000000000000000000000000000000000000000000001c57a9913ddaf1d53f582000380") 194 | // }); 195 | 196 | 197 | it('withdrawExit return tx', async () => { 198 | const result: ITransactionRequestConfig = await erc20Parent.withdrawExit('0x1c20c41b9d97d1026aa456a21f13725df63edec1b1f43aacb180ebcc6340a2d3', { 199 | returnTransaction: true 200 | }) as any; 201 | 202 | const rootChainManager = await abiManager.getConfig("Main.POSContracts.RootChainManagerProxy") 203 | expect(result['to'].toLowerCase()).equal(rootChainManager.toLowerCase()); 204 | 205 | 206 | expect(result.data).equal( 207 | "0x3805550f00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000827f9082484235e69b0b9010031f7f7ef8848837caca0654cdd16c2c1af23e138d5ea431107325c6d99dfa567b8e395866f4fd177d79de4a8fec9d06ecea4223f55d1724e6c8455dc62148394266f9e732545254f25407139bd8cb3ecfbd9053933f23e1fca181659680cf4c1a5a6c6f723df2d7d35f3fc14929c8ccef3a9fff644db162a845ecf3a89f41b98436f15fada0f112ebea28f29e9e97f3635bd68ff97de3c0f5cdbd867bd8cb13af5930f55ca3b9ee8f345c3923965d2935a72bb4ddff77b6d5a8f427fbe79945d58189e2f58bec6c09e38c058bb80978eee60bcc260c883be329eb37a9c029e7d5733a173b53aeb0e92f925db4dc681d4bfa2f05c8c5fdd296230d1411b05264a84013c786a84617a6c24a0a317bf456e88f02bccaab4c7aa1a919485ee451901772eeff615a2ab305f3ca0a0984131328f0f9b4ffba09638e99ce4ec98b1aec6eb46eb3023078a03be9d51f8b902ebf902e801830743f9b9010000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000008000000800000000000000000000100000000000000000000020000000000000000000800000000000000000080000010000000000000000000010000000008000000000000000000000000000000000000000000200000000000000020000000000000010001000000000000000000000000004000000003000000000001000000000000000000000000000000100000400020000000000000000000000000000000000000000000000000000000000000100000f901ddf89b94fe4f5145f6e09952a5ba9e956ed0c25e3fa4c7f1f863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca00000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000af9013d940000000000000000000000000000000000001010f884a04dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63a00000000000000000000000000000000000000000000000000000000000001010a0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca0000000000000000000000000c26880a0af2ea0c7e8130e6ec47af756465452e8b8a000000000000000000000000000000000000000000000000000005d17d8a0120000000000000000000000000000000000000000000000006f680513d061bb0d020000000000000000000000000000000000000000000001c57a98b6c5d67d41f500000000000000000000000000000000000000000000006f6804b6b8891afb020000000000000000000000000000000000000000000001c57a9913ddaf1d53f5b903dbf903d8f851a051de183267eca4127869bd2deab74a212d98ec445ea022f108006a65d32011b780808080808080a0f3099598ea2f187f803b8d66b328edf300720bfb016f4d89b4a1eceebf969f508080808080808080f89180a0ee5f307c063eefc1f9ad442f3b9f8f2981f9385b41da5465de5ac5dec863d5c7a0d5a8f8f4ab278e0aea28f1044da97c7bd3a5e807b48cd01bf705b704aa5ddd14a032a40b81b5316142b455addcb7bdd194be8e38196408efefcc4291803a402eeea0188088651f1f064c8fa57051108a83c9d695f1a124dc3783ed2a2e6e7c8fd21a808080808080808080808080f902ef20b902ebf902e801830743f9b9010000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000008000000800000000000000000000100000000000000000000020000000000000000000800000000000000000080000010000000000000000000010000000008000000000000000000000000000000000000000000200000000000000020000000000000010001000000000000000000000000004000000003000000000001000000000000000000000000000000100000400020000000000000000000000000000000000000000000000000000000000000100000f901ddf89b94fe4f5145f6e09952a5ba9e956ed0c25e3fa4c7f1f863a0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca00000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000af9013d940000000000000000000000000000000000001010f884a04dfe1bbbcf077ddc3e01291eea2d5c70c2b422b415d95645b9adcfd678cb1d63a00000000000000000000000000000000000000000000000000000000000001010a0000000000000000000000000fd71dc9721d9ddcf0480a582927c3dcd42f3064ca0000000000000000000000000c26880a0af2ea0c7e8130e6ec47af756465452e8b8a000000000000000000000000000000000000000000000000000005d17d8a0120000000000000000000000000000000000000000000000006f680513d061bb0d020000000000000000000000000000000000000000000001c57a98b6c5d67d41f500000000000000000000000000000000000000000000006f6804b6b8891afb020000000000000000000000000000000000000000000001c57a9913ddaf1d53f58200038000000000000000000000000000000000000000000000000000" 208 | ) 209 | }); 210 | 211 | it('child transfer', async () => { 212 | const oldBalance = await erc20Child.getBalance(to); 213 | console.log('oldBalance', oldBalance); 214 | const amount = 10; 215 | let result = await erc20Child.transfer(amount, to); 216 | let txHash = await result.getTransactionHash(); 217 | expect(txHash).to.be.an('string'); 218 | console.log('txHash', txHash); 219 | let txReceipt = await result.getReceipt(); 220 | console.log("txReceipt", txReceipt); 221 | 222 | expect(txReceipt.transactionHash).equal(txHash); 223 | expect(txReceipt).to.be.an('object'); 224 | expect(txReceipt.from.toLowerCase()).equal(from.toLowerCase()); 225 | expect(txReceipt.to.toLowerCase()).equal(erc20.child.toLowerCase()); 226 | expect(txReceipt.type).equal('0x2'); 227 | expect(txReceipt.gasUsed).to.be.an('number').gt(0); 228 | expect(txReceipt.cumulativeGasUsed).to.be.an('number').gt(0); 229 | 230 | expect(txReceipt).to.have.property('blockHash') 231 | expect(txReceipt).to.have.property('blockNumber'); 232 | expect(txReceipt).to.have.property('events'); 233 | // expect(txReceipt).to.have.property('logs'); 234 | expect(txReceipt).to.have.property('logsBloom'); 235 | expect(txReceipt).to.have.property('status'); 236 | expect(txReceipt).to.have.property('transactionIndex'); 237 | 238 | const newBalance = await erc20Child.getBalance(to); 239 | console.log('newBalance', newBalance); 240 | 241 | const oldBalanceBig = new BN(oldBalance); 242 | const newBalanceBig = new BN(newBalance); 243 | 244 | expect(newBalanceBig.toString()).equal( 245 | oldBalanceBig.add(new BN(amount)).toString() 246 | ) 247 | 248 | //transfer money back to user 249 | const erc20ChildToken = posClientForTo.erc20(erc20.child); 250 | 251 | result = await erc20ChildToken.transfer(amount, to); 252 | txHash = await result.getTransactionHash(); 253 | txReceipt = await result.getReceipt(); 254 | }); 255 | 256 | if (process.env.NODE_ENV !== 'test_all') return; 257 | 258 | it('approve', async () => { 259 | const result = await erc20Parent.approve('10'); 260 | 261 | const txHash = await result.getTransactionHash(); 262 | expect(txHash).to.be.an('string'); 263 | 264 | const txReceipt = await result.getReceipt(); 265 | console.log("txReceipt", txReceipt); 266 | expect(txReceipt.type).equal('0x0'); 267 | }); 268 | 269 | it('deposit', async () => { 270 | const result = await erc20Parent.deposit('10', from); 271 | 272 | const txHash = await result.getTransactionHash(); 273 | expect(txHash).to.be.an('string'); 274 | 275 | const txReceipt = await result.getReceipt(); 276 | expect(txReceipt).to.be.an('object'); 277 | }); 278 | 279 | }); 280 | -------------------------------------------------------------------------------- /test/specs/hex.spec.ts: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai' 2 | import { Converter, utils } from '@maticnetwork/maticjs' 3 | 4 | describe('Hex test', () => { 5 | 6 | 7 | it('Converter.toHex', () => { 8 | const value = Converter.toHex('10'); 9 | 10 | expect(value).equal('0xa'); 11 | }) 12 | 13 | it('BigNumber.toHex', () => { 14 | const value = new utils.BN('10').toString(16) 15 | 16 | expect(value).equal('a'); 17 | }) 18 | 19 | it('Converter.toHex with BN', () => { 20 | const value = Converter.toHex( 21 | new utils.BN(10) 22 | ); 23 | 24 | expect(value).equal('0xa'); 25 | }) 26 | 27 | it('amount is 593390000', () => { 28 | const amount = 593390000; 29 | const value = Converter.toHex( 30 | new utils.BN(amount) 31 | ); 32 | 33 | expect(value).equal('0x235e69b0'); 34 | expect('235e69b0').equal( 35 | new utils.BN(amount).toString(16) 36 | ); 37 | }) 38 | 39 | }); -------------------------------------------------------------------------------- /test/specs/index.ts: -------------------------------------------------------------------------------- 1 | import { use } from "@maticnetwork/maticjs"; 2 | import { Web3ClientPlugin } from "@maticnetwork/maticjs-web3"; 3 | 4 | use(Web3ClientPlugin); 5 | 6 | console.log('process.env.NODE_ENV', process.env.NODE_ENV); 7 | 8 | import './pos_bridge' 9 | import './hex.spec' 10 | import './erc20.spec' 11 | -------------------------------------------------------------------------------- /test/specs/pos_bridge.ts: -------------------------------------------------------------------------------- 1 | import { erc721, from, posClient, posClientForTo, privateKey, RPC, to, toPrivateKey } from "./client"; 2 | import { expect } from 'chai' 3 | import { ABIManager } from '@maticnetwork/maticjs' 4 | import HDWalletProvider from "@truffle/hdwallet-provider"; 5 | 6 | describe('POS Client', () => { 7 | 8 | const abiManager = new ABIManager("testnet", "mumbai"); 9 | 10 | 11 | before(() => { 12 | return Promise.all([ 13 | abiManager.init() 14 | ]); 15 | }); 16 | 17 | it("pos client from init", async () => { 18 | await posClient.init({ 19 | // log: true, 20 | network: 'testnet', 21 | version: 'mumbai', 22 | parent: { 23 | provider: new HDWalletProvider(privateKey, RPC.parent), 24 | defaultConfig: { 25 | from 26 | } 27 | }, 28 | child: { 29 | provider: new HDWalletProvider(privateKey, RPC.child), 30 | defaultConfig: { 31 | from 32 | } 33 | } 34 | }); 35 | }) 36 | 37 | it("pos client to init", async () => { 38 | await posClientForTo.init({ 39 | // log: true, 40 | network: 'testnet', 41 | version: 'mumbai', 42 | parent: { 43 | provider: new HDWalletProvider(toPrivateKey, RPC.parent), 44 | defaultConfig: { 45 | from: to 46 | } 47 | }, 48 | child: { 49 | provider: new HDWalletProvider(toPrivateKey, RPC.child), 50 | defaultConfig: { 51 | from: to 52 | } 53 | } 54 | }); 55 | }) 56 | 57 | const txHash = `0x92898987248eaec73dc56eee44f68084a2adcb13a83213590cce437d54aa17db`; 58 | it("null tx check getTransactionReceipt", async () => { 59 | try { 60 | await posClient.client.parent.getTransactionReceipt(txHash); 61 | throw "should have been error"; 62 | } catch (error) { 63 | expect(error).eql({ 64 | type: 'invalid_transaction' as any, 65 | message: 'Could not retrieve transaction. Either it is invalid or might be in archive node.' 66 | }); 67 | } 68 | }) 69 | 70 | it("null tx check getTransaction", async () => { 71 | try { 72 | await posClient.client.parent.getTransaction(txHash); 73 | throw "should have been error"; 74 | } catch (error) { 75 | expect(error).eql({ 76 | type: 'invalid_transaction' as any, 77 | message: 'Could not retrieve transaction. Either it is invalid or might be in archive node.' 78 | }); 79 | } 80 | }) 81 | }); 82 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": true, 3 | "compilerOptions": { 4 | "lib": ["es2015", "dom"], 5 | "target": "es5", 6 | "rootDir": "test", 7 | "resolveJsonModule": true, 8 | "esModuleInterop": true, 9 | "moduleResolution": "node", 10 | }, 11 | "exclude": [ 12 | "node_modules", 13 | "dist", 14 | "lib" 15 | ] 16 | } -------------------------------------------------------------------------------- /test/webpack.config.test.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack') 2 | const path = require('path') 3 | 4 | // return console.log('process.env', process.env.from) 5 | 6 | 7 | module.exports = { 8 | mode: 'development', 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.tsx?$/, 13 | use: 'ts-loader', 14 | exclude: /node_modules/, 15 | }, 16 | ], 17 | }, 18 | resolve: { 19 | extensions: ['.tsx', '.ts', '.js', '.json'], 20 | }, 21 | output: { 22 | filename: 'bundle.js', 23 | path: path.resolve(__dirname, 'bin/'), 24 | }, 25 | plugins: [ 26 | new webpack.DefinePlugin({ 27 | 'process.env': JSON.stringify(process.env), 28 | 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) 29 | }), 30 | ], 31 | devtool: 'inline-source-map', 32 | } 33 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "array-type": [ 4 | true, 5 | "array-simple" 6 | ], 7 | "arrow-return-shorthand": true, 8 | "ban": [ 9 | true, 10 | { 11 | "name": "parseFloat", 12 | "message": "tsstyle#type-coercion" 13 | }, 14 | { 15 | "name": "Array", 16 | "message": "tsstyle#array-constructor" 17 | } 18 | ], 19 | "ban-types": [ 20 | true, 21 | [ 22 | "Object", 23 | "Use {} instead." 24 | ], 25 | [ 26 | "String", 27 | "Use 'string' instead." 28 | ], 29 | [ 30 | "Number", 31 | "Use 'number' instead." 32 | ], 33 | [ 34 | "Boolean", 35 | "Use 'boolean' instead." 36 | ] 37 | ], 38 | "class-name": true, 39 | "curly": [ 40 | true, 41 | "ignore-same-line" 42 | ], 43 | // "forin": true, 44 | "interface-name": [ 45 | true, 46 | "allow-prefix" 47 | ], 48 | "jsdoc-format": true, 49 | "label-position": true, 50 | "member-access": [ 51 | true, 52 | "no-public" 53 | ], 54 | "new-parens": true, 55 | "no-angle-bracket-type-assertion": true, 56 | "no-any": false, 57 | "no-arg": true, 58 | "no-conditional-assignment": true, 59 | "no-construct": true, 60 | "no-debugger": true, 61 | "no-default-export": true, 62 | "no-duplicate-variable": true, 63 | "no-inferrable-types": true, 64 | "no-namespace": [ 65 | true, 66 | "allow-declarations" 67 | ], 68 | "no-reference": true, 69 | "no-string-throw": true, 70 | "no-unused-expression": true, 71 | "no-var-keyword": true, 72 | "object-literal-shorthand": false, 73 | "prefer-const": true, 74 | "semicolon": [ 75 | true, 76 | "always", 77 | "ignore-bound-class-methods" 78 | ], 79 | // "switch-default": true, 80 | "triple-equals": [ 81 | true, 82 | "allow-null-check" 83 | ], 84 | "use-isnan": true, 85 | "variable-name": [ 86 | true, 87 | "check-format", 88 | "ban-keywords", 89 | "allow-leading-underscore", 90 | "allow-trailing-underscore" 91 | ], 92 | "no-shadowed-variable": true, 93 | "naming-convention": [true, 94 | // this config will apply to properties AND methods, if you only need it for properties, use "property" instead of "member" 95 | {"type": "member", "format": "camelCase"}, // use camelCase for all members, will be inherited by protected and private 96 | {"type": "member", "modifiers": "protected", "trailingUnderscore": "require"}, // protected members will be REQUIRED to have a leading underscore. you can use "allow" as alternative 97 | {"type": "member", "modifiers": "private", "suffix": "__"} // to simply allow and not enforce double leading underscores, use "prefix": ["__", ""] 98 | ] 99 | } 100 | } -------------------------------------------------------------------------------- /webpack/licence.js: -------------------------------------------------------------------------------- 1 | const package = require('../package.json'); 2 | var today = new Date(); 3 | var dd = today.getDate(); 4 | var mm = today.getMonth() + 1; //January is 0! 5 | var yyyy = today.getFullYear(); 6 | if (dd < 10) { 7 | dd = '0' + dd; 8 | } 9 | if (mm < 10) { 10 | mm = '0' + mm; 11 | } 12 | var today = dd + '/' + mm + '/' + yyyy; 13 | 14 | exports.banner = `@license :${package.name} - V${package.version} - ${today} 15 | https://github.com/maticnetwork/maticjs-web3 16 | Copyright (c) ${yyyy} @polygon; Licensed ${package.license}`; -------------------------------------------------------------------------------- /webpack/webpack.base.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const copyPlugin = require('copy-webpack-plugin') 3 | const SmartBannerPlugin = require('smart-banner-webpack-plugin'); 4 | const banner = require('./licence'); 5 | 6 | const libraryName = 'matic-web3' 7 | exports.libraryName = libraryName; 8 | let mode = process.env.NODE_ENV 9 | const isProd = mode === 'production' 10 | exports.isProd = isProd; 11 | 12 | console.log('build runing for mode', mode); 13 | exports.default = { 14 | mode, 15 | devtool: 'source-map', 16 | entry: `./src/index.ts`, 17 | target: 'web', 18 | output: { 19 | path: path.join(__dirname, "./../dist"), 20 | filename: `${libraryName}.umd${isProd ? '.min' : ''}.js`, 21 | library: libraryName, 22 | libraryTarget: 'umd', 23 | // libraryExport: 'default', 24 | umdNamedDefine: true, 25 | }, 26 | module: { 27 | rules: [ 28 | { 29 | test: /\.ts$/, 30 | use: 'ts-loader', 31 | exclude: /node_modules/, 32 | }, 33 | ], 34 | }, 35 | externals: { 36 | web3: 'web3', 37 | '@maticnetwork/maticjs': '@maticnetwork/maticjs' 38 | }, 39 | resolve: { 40 | modules: [path.resolve(__dirname, 'src'), 'node_modules'], 41 | extensions: ['.json', '.js', '.ts', 'tsx'], 42 | alias: { 43 | // "@": path.resolve(__dirname, "./src") 44 | }, 45 | }, 46 | plugins: [ 47 | new copyPlugin({ 48 | patterns: [{ from: path.resolve('build_helper', 'npm.export.js'), to: '' }], 49 | }), 50 | new SmartBannerPlugin(banner) 51 | ], 52 | } -------------------------------------------------------------------------------- /webpack/webpack.node.config.js: -------------------------------------------------------------------------------- 1 | const webpackMerge = require("webpack-merge"); 2 | const { default: webpackBaseConfig, libraryName, isProd } = require("./webpack.base.config"); 3 | var webpack = require('webpack'); 4 | 5 | exports.default = webpackMerge(webpackBaseConfig, { 6 | target: 'node', 7 | output: { 8 | filename: `${libraryName}.node${isProd ? '.min' : ''}.js`, 9 | // globalObject: 'this', 10 | libraryTarget: 'commonjs2', 11 | }, 12 | plugins: [ 13 | new webpack.DefinePlugin({ 14 | 'process.env.BUILD_ENV': JSON.stringify("node") 15 | }), 16 | ], 17 | }) --------------------------------------------------------------------------------